diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 120000 index 0000000..fbb7ee0 --- /dev/null +++ b/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/node_modules/.bin/nodemon b/node_modules/.bin/nodemon new file mode 120000 index 0000000..1056ddc --- /dev/null +++ b/node_modules/.bin/nodemon @@ -0,0 +1 @@ +../nodemon/bin/nodemon.js \ No newline at end of file diff --git a/node_modules/.bin/nodetouch b/node_modules/.bin/nodetouch new file mode 120000 index 0000000..3409fdb --- /dev/null +++ b/node_modules/.bin/nodetouch @@ -0,0 +1 @@ +../touch/bin/nodetouch.js \ No newline at end of file diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/.bin/uuid b/node_modules/.bin/uuid new file mode 100644 index 0000000..c3ec003 --- /dev/null +++ b/node_modules/.bin/uuid @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../uuid/dist/bin/uuid" "$@" +else + exec node "$basedir/../uuid/dist/bin/uuid" "$@" +fi diff --git a/node_modules/.bin/uuid.cmd b/node_modules/.bin/uuid.cmd new file mode 100644 index 0000000..0f2376e --- /dev/null +++ b/node_modules/.bin/uuid.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\dist\bin\uuid" %* diff --git a/node_modules/.bin/uuid.ps1 b/node_modules/.bin/uuid.ps1 new file mode 100644 index 0000000..7804628 --- /dev/null +++ b/node_modules/.bin/uuid.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "$basedir/node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } else { + & "node$exe" "$basedir/../uuid/dist/bin/uuid" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..f73335d --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,1485 @@ +{ + "name": "Business_Analyst_AI", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@google/genai": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@google/genai/-/genai-0.7.0.tgz", + "integrity": "sha512-r+Fwj/emnXZN5R+4JCxDXboY4AGTmTn7+Wnori5dgyJiStP0P82f9YYL0CVsCnDIumNY2i0UIcZ1zGZdtHJ34w==", + "dependencies": { + "google-auth-library": "^9.14.2", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agent-base": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz", + "integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==", + "engines": { + "node": ">= 14" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/bignumber.js": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.1.2.tgz", + "integrity": "sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug==", + "engines": { + "node": "*" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "license": "MIT" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dotenv": { + "version": "16.4.7", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", + "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.21.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", + "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.7.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.12", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gaxios": { + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", + "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "is-stream": "^2.0.0", + "node-fetch": "^2.6.9", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/gcp-metadata": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz", + "integrity": "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==", + "dependencies": { + "gaxios": "^6.1.1", + "google-logging-utils": "^0.0.2", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/google-auth-library": { + "version": "9.15.1", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", + "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^6.1.1", + "gcp-metadata": "^6.1.0", + "gtoken": "^7.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/google-logging-utils": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz", + "integrity": "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==", + "engines": { + "node": ">=14" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gtoken": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", + "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", + "dependencies": { + "gaxios": "^6.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "license": "ISC" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/json-bigint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", + "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, + "node_modules/jwa": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", + "integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", + "integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", + "dependencies": { + "jwa": "^2.0.0", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/nodemon": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.9.tgz", + "integrity": "sha512-hdr1oIb2p6ZSxu3PB2JWWYS7ZQ0qvaZsc3hK8DR8f02kRzc8rjYmxAIvdz+aYC+8F2IjNaB7HMcSDg8nQpJxyg==", + "license": "MIT", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "license": "MIT" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "license": "MIT" + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz", + "integrity": "sha512-hlq8tAfn0m/61p4BVRcPzIGr6LKiMwo4VM6dGi6pt4qcRkmNzTcWq6eCEjEh+qXjkMDvPlOFFSGwQjoEa6gyMA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "license": "ISC", + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/node_modules/@google/genai/LICENSE b/node_modules/@google/genai/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@google/genai/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/node_modules/@google/genai/README.md b/node_modules/@google/genai/README.md new file mode 100644 index 0000000..7f0180f --- /dev/null +++ b/node_modules/@google/genai/README.md @@ -0,0 +1,255 @@ +# Google Gen AI SDK for TypeScript and JavaScript + +[![NPM Downloads](https://img.shields.io/npm/dw/%40google%2Fgenai)](https://www.npmjs.com/package/@google/genai) +[![Node Current](https://img.shields.io/node/v/%40google%2Fgenai)](https://www.npmjs.com/package/@google/genai) + +---------------------- +**Documentation:** https://googleapis.github.io/js-genai/ + +---------------------- + +The Google Gen AI JavaScript SDK is designed for +TypeScript and JavaScript developers to build applications powered by Gemini. The SDK +supports both the [Gemini Developer API](https://ai.google.dev/gemini-api/docs) +and [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview). + +The Google Gen AI SDK is designed to work with Gemini 2.0 features. + +> [!NOTE] +> **SDK Preview:** +> See: [Preview Launch](#preview-launch). + +> [!CAUTION] +> **API Key Security:** Avoid exposing API keys in client-side code. +> Use server-side implementations in production environments. + + +## Prerequisites + +* Node.js version 18 or later + +## Installation + +To install the SDK, run the following command: + +```shell +npm install @google/genai +``` + +## Quickstart + +The simplest way to get started is to using an API key from +[Google AI Studio](https://aistudio.google.com/apikey): + +```typescript +import {GoogleGenAI} from '@google/genai'; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); + +async function main() { + const response = await ai.models.generateContent({ + model: 'gemini-2.0-flash-001', + contents: 'Why is the sky blue?', + }); + console.log(response.text); +} + +main(); +``` + +## Web quickstart + +The package contents are also available unzipped in the +`package/` directory of the bucket, so an equivalent web example is: + +```html + + + + + + Using My Package + + + + + +``` + +## Initialization + +The Google Gen AI SDK provides support for both the +[Google AI Studio](https://ai.google.dev/gemini-api/docs) and +[Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview) + implementations of the Gemini API. + +### Gemini Developer API + +For server-side applications, initialize using an API key, which can +be acquired from [Google AI Studio](https://aistudio.google.com/apikey): + +```typescript +import { GoogleGenAI } from '@google/genai'; +const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); +``` + +#### Browser + +> [!CAUTION] +> **API Key Security:** Avoid exposing API keys in client-side code. +> Use server-side implementations in production environments. + +In the browser the initialization code is identical: + + +```typescript +import { GoogleGenAI } from '@google/genai'; +const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); +``` + +### Vertex AI + +Sample code for VertexAI initialization: + +```typescript +import { GoogleGenAI } from '@google/genai'; + +const ai = new GoogleGenAI({ + vertexai: true, + project: 'your_project', + location: 'your_location', +}); +``` + +## GoogleGenAI overview + +All API features are accessed through an instance of the `GoogleGenAI` classes. +The submodules bundle together related API methods: + +- [`ai.models`](https://googleapis.github.io/js-genai/classes/models.Models.html): + Use `models` to query models (`generateContent`, `generateImages`, ...), or + examine their metadata. +- [`ai.caches`](https://googleapis.github.io/js-genai/classes/caches.Caches.html): + Create and manage `caches` to reduce costs when repeatedly using the same + large prompt prefix. +- [`ai.chats`](https://googleapis.github.io/js-genai/classes/chats.Chats.html): + Create local stateful `chat` objects to simplify multi turn interactions. +- [`ai.files`](https://googleapis.github.io/js-genai/classes/files.Files.html): + Upload `files` to the API and reference them in your prompts. + This reduces bandwidth if you use a file many times, and handles files too + large to fit inline with your prompt. +- [`ai.live`](https://googleapis.github.io/js-genai/classes/live.Live.html): + Start a `live` session for real time interaction, allows text + audio + video + input, and text or audio output. + +## Samples + +More samples can be found in the +[github samples directory](https://github.com/googleapis/js-genai/tree/main/sdk-samples). + + +### Streaming + +For quicker, more responsive API interactions use the `generateContentStream` +method which yields chunks as they're generated: + +```typescript +import {GoogleGenAI} from '@google/genai'; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); + +async function main() { + const response = await ai.models.generateContentStream({ + model: 'gemini-2.0-flash-001', + contents: 'Write a 100-word poem.', + }); + for await (const chunk of response) { + console.log(chunk.text); + } +} + +main(); +``` + +### Function Calling + +To let Gemini to interact with external systems, you can provide provide +`functionDeclaration` objects as `tools`. To use these tools it's a 4 step + +1. **Declare the function name, description, and parameters** +2. **Call `generateContent` with function calling enabled** +3. **Use the returned `FunctionCall` parameters to call your actual function** +3. **Send the result back to the model (with history, easier in `ai.chat`) + as a `FunctionResponse`** + +```typescript +import {GoogleGenAI, FunctionCallingConfigMode, FunctionDeclaration, Type} from '@google/genai'; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +async function main() { + const controlLightDeclaration: 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 ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); + const response = await ai.models.generateContent({ + model: 'gemini-2.0-flash-001', + contents: 'Dim the lights so the room feels cozy and warm.', + config: { + toolConfig: { + functionCallingConfig: { + // Force it to call any function + mode: FunctionCallingConfigMode.ANY, + allowedFunctionNames: ['controlLight'], + } + }, + tools: [{functionDeclarations: [controlLightDeclaration]}] + } + }); + + console.log(response.functionCalls); +} + +main(); +``` + + +## Preview Launch + +The SDK is curently in a preview launch stage, per [Google's launch stages](https://cloud.google.com/products?hl=en#section-22) this means: + +> At Preview, products or features are ready for testing by customers. Preview offerings are often publicly announced, but are not necessarily feature-complete, and no SLAs or technical support commitments are provided for these. Unless stated otherwise by Google, Preview offerings are intended for use in test environments only. The average Preview stage lasts about six months. + diff --git a/node_modules/@google/genai/dist/genai.d.ts b/node_modules/@google/genai/dist/genai.d.ts new file mode 100644 index 0000000..c2ced80 --- /dev/null +++ b/node_modules/@google/genai/dist/genai.d.ts @@ -0,0 +1,3658 @@ +import { GoogleAuthOptions } from 'google-auth-library'; + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * 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 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, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +declare class BaseModule { +} + +/** Content blob. */ +declare interface Blob_2 { + /** Required. Raw bytes. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob } + +export declare enum BlockedReason { + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + SAFETY = "SAFETY", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT" +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: (params?: types.ListCachedContentsParameters) => Promise>; + /** + * 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 [Vertex AI 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-1.5-flash', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create(params: types.CreateCachedContentParameters): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: 'gemini-1.5-flash'}); + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * 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: 'gemini-1.5-flash'}); + * ``` + */ + delete(params: types.DeleteCachedContentParameters): Promise; + /** + * 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: 'gemini-1.5-flash', + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update(params: types.UpdateCachedContentParameters): Promise; + private listInternal; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor(apiClient: ApiClient, modelsModule: Models, model: string, config?: types.GenerateContentConfig, history?: types.Content[]); + /** + * 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); + * ``` + */ + sendMessage(params: types.SendMessageParameters): Promise; + /** + * 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); + * } + * ``` + */ + sendMessageStream(params: types.SendMessageParameters): Promise>; + /** + * 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?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, 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: types.CreateChatParameters): Chat; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +declare namespace common { + export { + formatMap, + setValueByPath, + getValueByPath, + BaseModule, + UploadFileParameters + } +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + left blank or unset. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = ContentUnion[] | ContentUnion; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** 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. + */ +export declare interface ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; +} + +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH" +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-1.5-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-1.5-pro', etc. See gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent(partOrString: PartListUnion | string): Content; + +/** + * Creates a `Part` object from a `base64` `string`. + */ +export declare function createPartFromBase64(data: string, mimeType: string): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult(outcome: Outcome, output: string): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode(code: string, language: Language): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall(name: string, args: Record): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse(id: string, name: string, response: Record): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent(partOrString: PartListUnion | string): Content; + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse { +} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse { +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +export declare enum DynamicRetrievalConfigMode { + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [FunctionDeclaration] tool and [FunctionCallingConfig] mode is set to [Mode.CODE]. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File } + +/** URI based data. */ +export declare interface FileData { + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in 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. + * Somex eamples 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 + * `common.UploadFileParameters` interface. + * @return A promise that resolves to a `types.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, + * 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); + * ``` + */ + upload(params: common.UploadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * 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); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * 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}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED" +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED" +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +export declare enum FinishReason { + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + STOP = "STOP", + MAX_TOKENS = "MAX_TOKENS", + SAFETY = "SAFETY", + RECITATION = "RECITATION", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + SPII = "SPII", + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + IMAGE_SAFETY = "IMAGE_SAFETY" +} + +declare function formatMap(templateString: string, valueMap: Record): string; + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. Required. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +export declare enum FunctionCallingConfigMode { + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + AUTO = "AUTO", + ANY = "ANY", + NONE = "NONE" +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Describes the output from the function in the OpenAPI JSON Schema + Object format. */ + response?: Schema; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; +} + +/** A function response. */ +export declare class FunctionResponse { + /** The id of the function call this response is for. Populated by the client + to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response media type of the generated candidate text. + */ + responseMimeType?: string; + /** Schema that the generated candidate text must adhere to. + */ + responseSchema?: SchemaUnion; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** Identifier for each response. + */ + responseId?: string; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * 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(): string | 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(): FunctionCall[] | undefined; + /** + * 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(): string | undefined; + /** + * 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(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. + */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. + */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. + */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. + */ + enhancedPrompt?: string; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** Whether to use the prompt rewriting logic. + */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** List of generated images. + */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. + */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 1280x720, 1920x1080 are supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation progress. */ + pubsubTopic?: string; + /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** A video generation operation. */ +export declare interface GenerateVideosOperation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The normal response of the operation in case of success. */ + response?: Record; + /** The generated videos. */ + result?: GenerateVideosResponse; +} + +/** Class that represents the parameters for generating an image. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. Optional for image to video use cases. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt is provided. */ + image?: Image_2; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: 'UNKNOWN' | 'PRIORITIZE_QUALITY' | 'BALANCED' | 'PRIORITIZE_COST'; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. e.g. 'gemini-1.5-pro-001'. */ + modelName?: string; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +declare function getValueByPath(data: unknown, keys: string[]): unknown; + +/** + * 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 {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @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' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project region for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. This list must have the same size as the grounding_chunk_indices. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +export declare enum HarmBlockMethod { + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + SEVERITY = "SEVERITY", + PROBABILITY = "PROBABILITY" +} + +export declare enum HarmBlockThreshold { + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE", + OFF = "OFF" +} + +export declare enum HarmCategory { + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY" +} + +export declare enum HarmProbability { + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + NEGLIGIBLE = "NEGLIGIBLE", + LOW = "LOW", + MEDIUM = "MEDIUM", + HIGH = "HIGH" +} + +export declare enum HarmSeverity { + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH" +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE'; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. + */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image } + +export declare enum ImagePromptLanguage { + auto = "auto", + en = "en", + ja = "ja", + ko = "ko", + hi = "hi" +} + +export declare enum Language { + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + PYTHON = "PYTHON" +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental + + @remarks + If using the Gemini API, Live is currently only supported behind API + version `v1alpha`. Ensure that the API version is set to `v1alpha` when + initializing the SDK if relying on the Gemini API. + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + 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.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + onopen?: (() => void) | null; + onmessage: (e: LiveServerMessage) => void; + onerror?: ((e: ErrorEvent) => void) | null; + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `ClientContentUpdate` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `ClientContentUpdate` and the `RealtimeUpdate`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + + The following fields are supported: + - `response_logprobs` + - `response_mime_type` + - `logprobs` + - `response_schema` + - `stop_sequence` + - `routing_config` + - `audio_timestamp` + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: Content; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; +} + +/** 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. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: Content; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media: Blob_2; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; +} + +/** Response message for API call. */ +export declare interface LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; +} + +/** Sent in response to a `LiveGenerateContentSetup` message from the client. */ +export declare interface LiveServerSetupComplete { +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** 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. + */ +export declare interface MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; +} + +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC" +} + +export declare enum MediaModality { + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + TEXT = "TEXT", + IMAGE = "IMAGE", + VIDEO = "VIDEO", + AUDIO = "AUDIO", + DOCUMENT = "DOCUMENT" +} + +export declare enum MediaResolution { + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH" +} + +export declare enum Modality { + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + TEXT = "TEXT", + IMAGE = "IMAGE", + AUDIO = "AUDIO" +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +export declare enum Mode { + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI 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); + * ``` + */ + generateContent: (params: types.GenerateContentParameters) => Promise; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI 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); + * } + * ``` + */ + generateContentStream: (params: types.GenerateContentParameters) => Promise>; + /** + * Generates an image based on a text description and configuration. + * + * @param model - The model to use. + * @param prompt - A text description of the image to generate. + * @param [config] - The config for image generation. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: (params: types.GenerateImagesParameters) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * 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); + * ``` + */ + embedContent(params: types.EmbedContentParameters): Promise; + /** + * 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 ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + private generateImagesInternal; + /** + * 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); + * ``` + */ + countTokens(params: types.CountTokensParameters): Promise; + /** + * 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); + * ``` + */ + computeTokens(params: types.ComputeTokensParameters): Promise; + /** + * 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', + * 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.get({operation: operation}); + * } + * + * console.log(operation.result?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos(params: types.GenerateVideosParameters): Promise; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters { + /** The operation to be retrieved. */ + operation: GenerateVideosOperation; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param operation The Operation object returned by a previous API call. + * @return The updated Operation object, with the latest status or result. + */ + get(parameters: types.OperationGetParameters): Promise; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +export declare enum Outcome { + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + OUTCOME_OK = "OUTCOME_OK", + OUTCOME_FAILED = "OUTCOME_FAILED", + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED" +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Pagers for the GenAI List APIs. + */ +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents" +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + protected requestInternal: (params: PagedItemConfig) => Promise>; + protected idxInternal: number; + constructor(name: PagedItem, request: (params: PagedItemConfig) => Promise>, response: PagedItemResponse, params: PagedItemConfig); + private init; + private initNextPage; + /** + * 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(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * 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(): number; + /** + * 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(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * 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](): AsyncIterator; + /** + * 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(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. URI based data. */ + fileData?: FileData; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +export declare type PartUnion = Part | string; + +export declare enum PersonGeneration { + DONT_ALLOW = "DONT_ALLOW", + ALLOW_ADULT = "ALLOW_ADULT", + ALLOW_ALL = "ALLOW_ALL" +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. + */ + voiceName?: string; +} + +/** 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. + */ +export declare interface RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. + */ + categories?: string[]; + /** List of scores of each categories. + */ + scores?: number[]; + /** Internal use only. + */ + contentType?: string; +} + +export declare enum SafetyFilterLevel { + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE" +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Schema that defines the format of input and output data. + + Represents a select subset of an OpenAPI 3.0 schema object. + */ +export declare interface Schema { + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema; + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClientRealtimeInput; + private tLiveClienttToolResponse; + /** + 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: types.LiveSendClientContentParameters): void; + /** + 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: types.LiveSendRealtimeInputParameters): void; + /** + 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: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +declare function setValueByPath(data: Record, keys: string[], value: unknown): void; + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +export declare enum State { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + ACTIVE = "ACTIVE", + ERROR = "ERROR" +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** 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. + */ +export declare interface StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** 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. + */ +export declare interface SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; +} + +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT" +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional. Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. This field is only used by the Gemini Developer API services. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution { +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; +} + +export declare type ToolListUnion = Tool[]; + +export declare enum Type { + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + STRING = "STRING", + NUMBER = "NUMBER", + INTEGER = "INTEGER", + BOOLEAN = "BOOLEAN", + ARRAY = "ARRAY", + OBJECT = "OBJECT" +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + Modality, + State, + DynamicRetrievalConfigMode, + FunctionCallingConfigMode, + MediaResolution, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + FileState, + FileSource, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + MediaModality, + VideoMetadata, + CodeExecutionResult, + ExecutableCode, + FileData, + FunctionCall, + FunctionResponse, + Blob_2 as Blob, + Part, + Content, + HttpOptions, + Schema, + SafetySetting, + FunctionDeclaration, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + VertexAISearch, + VertexRagStoreRagResource, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeechConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + GoogleTypeDate, + Citation, + CitationMetadata, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + GenerateVideosConfig, + GenerateVideosParameters, + Video, + GeneratedVideo, + GenerateVideosResponse, + GenerateVideosOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + HttpResponse, + LiveCallbacks, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceConfig, + MaskReferenceImage, + ControlReferenceConfig, + ControlReferenceImage, + StyleReferenceConfig, + StyleReferenceImage, + SubjectReferenceConfig, + SubjectReferenceImage, + LiveServerSetupComplete, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + LiveServerMessage, + LiveClientSetup, + LiveClientContent, + LiveClientRealtimeInput, + LiveClientToolResponse, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendRealtimeInputParameters, + LiveSendToolResponseParameters, + OperationGetParameters, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolListUnion + } +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload(file: string | Blob, uploadUrl: string, apiClient: ApiClient): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression if the ``output_mime_type`` is + ``image/jpeg``. */ + outputCompressionQuality?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. */ + videoBytes?: string; + /** Video encoding, for example "video/mp4". */ + mimeType?: string; +} + +/** Metadata describes the input video content. */ +export declare interface VideoMetadata { + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create(url: string, headers: Record, callbacks: WebSocketCallbacks): WebSocket_2; +} + +export { } diff --git a/node_modules/@google/genai/dist/index.js b/node_modules/@google/genai/dist/index.js new file mode 100644 index 0000000..7f6e773 --- /dev/null +++ b/node_modules/@google/genai/dist/index.js @@ -0,0 +1,7890 @@ +'use strict'; + +/** + * @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 { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + 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 undefined; + } + 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 undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @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 (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 tPart(apiClient, 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(apiClient, 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(apiClient, item)); + } + return [tPart(apiClient, 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 _isUserPart(origin) { + if (origin === null || origin === undefined) { + return false; + } + if (_isFunctionCallPart(origin)) { + return false; + } + return true; +} +function _areUserParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + return false; + } + return origin.every(_isUserPart); +} +function tContent(apiClient, origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // @ts-expect-error: _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + if (_isUserPart(origin)) { + return { + role: 'user', + parts: tParts(apiClient, origin), + }; + } + else { + return { + role: 'model', + parts: tParts(apiClient, origin), + }; + } +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(apiClient, 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(apiClient, 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(apiClient, item)); + } + return [tContent(apiClient, origin)]; +} +function _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts) { + if (accumulatedParts.length === 0) { + return; + } + if (_areUserParts(accumulatedParts)) { + result.push({ + role: 'user', + parts: tParts(apiClient, accumulatedParts), + }); + } + else { + result.push({ + role: 'model', + parts: tParts(apiClient, accumulatedParts), + }); + } + accumulatedParts.length = 0; // clear the array inplace +} +function _handleCurrentPart(apiClient, result, accumulatedParts, currentPart) { + if (_isUserPart(currentPart) === _areUserParts(accumulatedParts)) { + accumulatedParts.push(currentPart); + } + else { + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + accumulatedParts.length = 0; + accumulatedParts.push(currentPart); + } +} +function tContents(apiClient, origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + return [tContent(apiClient, origin)]; + } + const result = []; + const accumulatedParts = []; + for (const content of origin) { + if (_isContent(content)) { + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + // @ts-expect-error: content is a Content here + result.push(content); + } + else if (typeof content === 'string' || + (typeof content === 'object' && !Array.isArray(content))) { + // @ts-expect-error: content is a part here + _handleCurrentPart(apiClient, result, accumulatedParts, content); + } + else if (Array.isArray(content)) { + // if there're consecutive user parts before the list, + // convert to UserContent and append to result + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + result.push({ + role: 'user', + parts: tParts(apiClient, content), + }); + } + else { + throw new Error(`Unsupported content type: ${typeof content}`); + } + } + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + return result; +} +function processSchema(apiClient, schema) { + if (!apiClient.isVertexAI()) { + if ('default' in schema) { + throw new Error('Default value is not supported in the response schema for the Gemini API.'); + } + } + if ('anyOf' in schema) { + if (schema['anyOf'] !== undefined) { + for (const subSchema of schema['anyOf']) { + processSchema(apiClient, subSchema); + } + } + } + if ('items' in schema) { + if (schema['items'] !== undefined) { + processSchema(apiClient, schema['items']); + } + } + if ('properties' in schema) { + if (schema['properties'] !== undefined) { + for (const subSchema of Object.values(schema['properties'])) { + processSchema(apiClient, subSchema); + } + } + } +} +function tSchema(apiClient, schema) { + processSchema(apiClient, schema); + return schema; +} +function tSpeechConfig(apiClient, speechConfig) { + if (typeof speechConfig === 'object' && 'voiceConfig' in speechConfig) { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tTool(apiClient, tool) { + return tool; +} +function tTools(apiClient, tool) { + if (!Array.isArray(tool)) { + throw new Error('tool is required and must be an array of Tools'); + } + return tool; +} +/** + * 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 tBytes(apiClient, fromImageBytes) { + if (typeof fromImageBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromImageBytes; +} +function tFileName(apiClient, fromName) { + if (typeof fromName !== 'string') { + throw new Error('fromName must be a string'); + } + // Remove the files/ prefx for MLdev urls to get the actual name of the file. + if (fromName.startsWith('files/')) { + return fromName.split('files/')[1]; + } + return fromName; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function partToMldev$1(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['videoMetadata']) !== undefined) { + throw new Error('videoMetadata parameter is not supported in Gemini API.'); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$1(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['response']) !== undefined) { + throw new Error('response parameter is not supported in Gemini API.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToMldev$1() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(apiClient, 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) { + if (Array.isArray(fromContents)) { + setValueByPath(parentObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev$1(apiClient, item); + }))); + } + else { + setValueByPath(parentObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(apiClient, fromToolConfig)); + } + 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) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(apiClient, 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) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(apiClient, 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(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function functionDeclarationToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], schemaToVertex$1(apiClient, fromResponse)); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToVertex$1() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(apiClient, 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) { + if (Array.isArray(fromContents)) { + setValueByPath(parentObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex$1(apiClient, item); + }))); + } + else { + setValueByPath(parentObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$1(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(apiClient, fromToolConfig)); + } + 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) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(apiClient, 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 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) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(apiClient, 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 listCachedContentsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(apiClient, 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 fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + if (Array.isArray(fromCachedContents)) { + setValueByPath(toObject, ['cachedContents'], fromCachedContents.map((item) => { + return cachedContentFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['cachedContents'], fromCachedContents); + } + } + return toObject; +} +function cachedContentFromVertex(apiClient, 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 fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + if (Array.isArray(fromCachedContents)) { + setValueByPath(toObject, ['cachedContents'], fromCachedContents.map((item) => { + return cachedContentFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['cachedContents'], fromCachedContents); + } + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Pagers for the GenAI List APIs. + */ +exports.PagedItem = void 0; +(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"; +})(exports.PagedItem || (exports.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.idxInternal = 0; + let requestParams = { config: {} }; + if (!params) { + 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 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 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +exports.Outcome = void 0; +(function (Outcome) { + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(exports.Outcome || (exports.Outcome = {})); +exports.Language = void 0; +(function (Language) { + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + Language["PYTHON"] = "PYTHON"; +})(exports.Language || (exports.Language = {})); +exports.Type = void 0; +(function (Type) { + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + Type["STRING"] = "STRING"; + Type["NUMBER"] = "NUMBER"; + Type["INTEGER"] = "INTEGER"; + Type["BOOLEAN"] = "BOOLEAN"; + Type["ARRAY"] = "ARRAY"; + Type["OBJECT"] = "OBJECT"; +})(exports.Type || (exports.Type = {})); +exports.HarmCategory = void 0; +(function (HarmCategory) { + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; +})(exports.HarmCategory || (exports.HarmCategory = {})); +exports.HarmBlockMethod = void 0; +(function (HarmBlockMethod) { + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(exports.HarmBlockMethod || (exports.HarmBlockMethod = {})); +exports.HarmBlockThreshold = void 0; +(function (HarmBlockThreshold) { + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + HarmBlockThreshold["OFF"] = "OFF"; +})(exports.HarmBlockThreshold || (exports.HarmBlockThreshold = {})); +exports.Mode = void 0; +(function (Mode) { + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.Mode || (exports.Mode = {})); +exports.FinishReason = void 0; +(function (FinishReason) { + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + FinishReason["STOP"] = "STOP"; + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + FinishReason["SAFETY"] = "SAFETY"; + FinishReason["RECITATION"] = "RECITATION"; + FinishReason["OTHER"] = "OTHER"; + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + FinishReason["SPII"] = "SPII"; + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(exports.FinishReason || (exports.FinishReason = {})); +exports.HarmProbability = void 0; +(function (HarmProbability) { + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + HarmProbability["LOW"] = "LOW"; + HarmProbability["MEDIUM"] = "MEDIUM"; + HarmProbability["HIGH"] = "HIGH"; +})(exports.HarmProbability || (exports.HarmProbability = {})); +exports.HarmSeverity = void 0; +(function (HarmSeverity) { + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(exports.HarmSeverity || (exports.HarmSeverity = {})); +exports.BlockedReason = void 0; +(function (BlockedReason) { + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + BlockedReason["SAFETY"] = "SAFETY"; + BlockedReason["OTHER"] = "OTHER"; + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; +})(exports.BlockedReason || (exports.BlockedReason = {})); +exports.Modality = void 0; +(function (Modality) { + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + Modality["TEXT"] = "TEXT"; + Modality["IMAGE"] = "IMAGE"; + Modality["AUDIO"] = "AUDIO"; +})(exports.Modality || (exports.Modality = {})); +exports.State = void 0; +(function (State) { + State["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + State["ACTIVE"] = "ACTIVE"; + State["ERROR"] = "ERROR"; +})(exports.State || (exports.State = {})); +exports.DynamicRetrievalConfigMode = void 0; +(function (DynamicRetrievalConfigMode) { + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.DynamicRetrievalConfigMode || (exports.DynamicRetrievalConfigMode = {})); +exports.FunctionCallingConfigMode = void 0; +(function (FunctionCallingConfigMode) { + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + FunctionCallingConfigMode["AUTO"] = "AUTO"; + FunctionCallingConfigMode["ANY"] = "ANY"; + FunctionCallingConfigMode["NONE"] = "NONE"; +})(exports.FunctionCallingConfigMode || (exports.FunctionCallingConfigMode = {})); +exports.MediaResolution = void 0; +(function (MediaResolution) { + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(exports.MediaResolution || (exports.MediaResolution = {})); +exports.SafetyFilterLevel = void 0; +(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"; +})(exports.SafetyFilterLevel || (exports.SafetyFilterLevel = {})); +exports.PersonGeneration = void 0; +(function (PersonGeneration) { + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(exports.PersonGeneration || (exports.PersonGeneration = {})); +exports.ImagePromptLanguage = void 0; +(function (ImagePromptLanguage) { + ImagePromptLanguage["auto"] = "auto"; + ImagePromptLanguage["en"] = "en"; + ImagePromptLanguage["ja"] = "ja"; + ImagePromptLanguage["ko"] = "ko"; + ImagePromptLanguage["hi"] = "hi"; +})(exports.ImagePromptLanguage || (exports.ImagePromptLanguage = {})); +exports.FileState = void 0; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(exports.FileState || (exports.FileState = {})); +exports.FileSource = void 0; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(exports.FileSource || (exports.FileSource = {})); +exports.MaskReferenceMode = void 0; +(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"; +})(exports.MaskReferenceMode || (exports.MaskReferenceMode = {})); +exports.ControlReferenceType = void 0; +(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"; +})(exports.ControlReferenceType || (exports.ControlReferenceType = {})); +exports.SubjectReferenceType = void 0; +(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"; +})(exports.SubjectReferenceType || (exports.SubjectReferenceType = {})); +exports.MediaModality = void 0; +(function (MediaModality) { + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + MediaModality["TEXT"] = "TEXT"; + MediaModality["IMAGE"] = "IMAGE"; + MediaModality["VIDEO"] = "VIDEO"; + MediaModality["AUDIO"] = "AUDIO"; + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(exports.MediaModality || (exports.MediaModality = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * 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) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * 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), + }; +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +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' && + (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 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 counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** 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(); + } +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** 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 = []; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.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 [Vertex AI 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-1.5-flash', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + 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: 'gemini-1.5-flash'}); + * ``` + */ + async get(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + 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: 'gemini-1.5-flash'}); + * ``` + */ + async delete(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + 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: 'gemini-1.5-flash', + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(this.apiClient, 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 __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; + } + if (part.text !== undefined && part.text === '') { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @remarks + * Expects the history to start with a user turn and then alternate between + * user and model turns. + * + * @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; + } + if (history[0].role !== 'user') { + throw new Error('History must start with a user turn.'); + } + 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; + let userInput = comprehensiveHistory[0]; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + userInput = 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(userInput); + curatedHistory.push(...modelOutput); + } + } + } + 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, 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(this.apiClient, 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; + 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; + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput); + return; + })(); + await this.sendPromise; + 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(this.apiClient, 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, + }); + this.sendPromise = streamResponse.then(() => 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) { + return curated ? extractCuratedHistory(this.history) : this.history; + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.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 && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role === 'model')) { + 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: [], + }); + } + this.history.push(userInput); + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '0.7.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 responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * Client errors raised by the GenAI API. + */ +class ClientError extends Error { + constructor(message, stackTrace) { + if (stackTrace) { + super(message, { cause: stackTrace }); + } + else { + super(message, { cause: new Error().stack }); + } + this.message = message; + this.name = 'ClientError'; + } +} +/** + * Server errors raised by the GenAI API. + */ +class ServerError extends Error { + constructor(message, stackTrace) { + if (stackTrace) { + super(message, { cause: stackTrace }); + } + else { + super(message, { cause: new Error().stack }); + } + this.message = message; + this.name = 'ServerError'; + } +} +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + // Assume that proj/api key validation occurs before they are passed in. + if (this.getProject() || this.getLocation()) { + initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + this.clientOptions.apiKey = undefined; // unset API key. + } + else { + initHttpOptions.baseUrl = `https://aiplatform.googleapis.com/`; + this.clientOptions.project = undefined; // unset project. + this.clientOptions.location = undefined; // unset location. + } + } + else { + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : 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; + } + 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 = '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) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (this.clientOptions.vertexai && + !this.clientOptions.apiKey && + !path.startsWith('projects/')) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const url = this.constructUrl(request.path, patchedHttpOptions); + 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); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + 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 url = this.constructUrl(request.path, patchedHttpOptions); + 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); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions) { + if (httpOptions && httpOptions.timeout && httpOptions.timeout > 0) { + const abortController = new AbortController(); + const signal = abortController.signal; + setTimeout(() => abortController.abort(), httpOptions.timeout); + requestInit.signal = signal; + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + 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 = ''; + 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); + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const chunkData = JSON.parse(processedChunkString); + yield yield __await(chunkData); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + 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) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * 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 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 uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + 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 ServerError('response is undefined'); + } + if (!response.ok) { + const status = response.status; + const statusText = response.statusText; + 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: 'exception parsing response', + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = `got status: ${status} ${statusText}. ${JSON.stringify(errorBody)}`; + if (status >= 400 && status < 500) { + const clientError = new ClientError(errorMessage); + throw clientError; + } + else if (status >= 500 && status < 600) { + const serverError = new ServerError(errorMessage); + throw serverError; + } + throw new Error(errorMessage); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function crossError() { + // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports + return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either: + +*Enabling conditional exports for your project [recommended]* + +*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'. +`); +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +class CrossUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + async stat(file) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return getBlobStat(file); + } + } +} +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b; + 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'; + } + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-status']) !== '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.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b['x-goog-upload-status']) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO((b/401271082): re-enable lint once CrossWebSocketFactory is implemented. +/* eslint-disable @typescript-eslint/no-unused-vars */ +class CrossWebSocketFactory { + create(url, headers, callbacks) { + throw crossError(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function listFilesConfigToMldev(apiClient, 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(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(apiClient, fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(apiClient, 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 fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(apiClient, fromError)); + } + return toObject; +} +function createFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(apiClient, fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(apiClient, 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 fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(apiClient, fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + if (Array.isArray(fromFiles)) { + setValueByPath(toObject, ['files'], fromFiles.map((item) => { + return fileFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['files'], fromFiles); + } + } + return toObject; +} +function createFileResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromHttpHeaders = getValueByPath(fromObject, ['httpHeaders']); + if (fromHttpHeaders != null) { + setValueByPath(toObject, ['httpHeaders'], fromHttpHeaders); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.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 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. + * Somex eamples 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 + * `common.UploadFileParameters` interface. + * @return A promise that resolves to a `types.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, + * 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('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(this.apiClient, response); + return file; + }); + } + async listInternal(params) { + var _a; + 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(this.apiClient, params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a; + 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(this.apiClient, params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(this.apiClient, 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; + 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(this.apiClient, params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(this.apiClient, apiResponse); + 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; + 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(this.apiClient, params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function partToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['videoMetadata']) !== undefined) { + throw new Error('videoMetadata parameter is not supported in Gemini API.'); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToMldev(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['example']) !== undefined) { + throw new Error('example parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['pattern']) !== undefined) { + throw new Error('pattern parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['default']) !== undefined) { + throw new Error('default parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['maxLength']) !== undefined) { + throw new Error('maxLength parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['minLength']) !== undefined) { + throw new Error('minLength parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['minProperties']) !== undefined) { + throw new Error('minProperties parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['maxProperties']) !== undefined) { + throw new Error('maxProperties parameter is not supported in Gemini API.'); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['response']) !== undefined) { + throw new Error('response parameter is not supported in Gemini API.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToMldev() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(apiClient, fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(apiClient, fromVoiceConfig)); + } + return toObject; +} +function thinkingConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev(apiClient, tContent(apiClient, 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'], schemaToMldev(apiClient, tSchema(apiClient, fromResponseSchema))); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + if (Array.isArray(fromSafetySettings)) { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings.map((item) => { + return safetySettingToMldev(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings); + } + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], tTools(apiClient, tTools(apiClient, fromTools).map((item) => { + return toolToMldev(apiClient, tTool(apiClient, item)); + }))); + } + else { + setValueByPath(parentObject, ['tools'], tTools(apiClient, fromTools)); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(apiClient, fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + 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'], speechConfigToMldev(apiClient, tSpeechConfig(apiClient, fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(apiClient, fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(apiClient, 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 not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + 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); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + 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); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function countTokensConfigToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(apiClient, fromConfig)); + } + return toObject; +} +function imageToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(apiClient, fromObject, parentObject) { + 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 not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + 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 not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + if (getValueByPath(fromObject, ['resolution']) !== undefined) { + throw new Error('resolution parameter is not supported in Gemini API.'); + } + 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 not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + 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(apiClient, fromImage)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToVertex(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(apiClient, fromObject) { + const toObject = {}; + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(apiClient, fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], schemaToVertex(apiClient, fromResponse)); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToVertex() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(apiClient, fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(apiClient, fromVoiceConfig)); + } + return toObject; +} +function thinkingConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(apiClient, tContent(apiClient, 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'], schemaToVertex(apiClient, tSchema(apiClient, fromResponseSchema))); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + if (Array.isArray(fromSafetySettings)) { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings.map((item) => { + return safetySettingToVertex(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings); + } + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], tTools(apiClient, tTools(apiClient, fromTools).map((item) => { + return toolToVertex(apiClient, tTool(apiClient, item)); + }))); + } + else { + setValueByPath(parentObject, ['tools'], tTools(apiClient, fromTools)); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(apiClient, 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(apiClient, tSpeechConfig(apiClient, fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(apiClient, fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(apiClient, fromObject, parentObject) { + 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 fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function countTokensConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToVertex(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function imageToVertex(apiClient, fromObject) { + 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(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToVertex(apiClient, fromObject, parentObject) { + 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); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + 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(apiClient, fromImage)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function candidateFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(apiClient, fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(apiClient, 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 fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + 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) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + if (Array.isArray(fromCandidates)) { + setValueByPath(toObject, ['candidates'], fromCandidates.map((item) => { + return candidateFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['candidates'], fromCandidates); + } + } + 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 fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + if (Array.isArray(fromEmbeddings)) { + setValueByPath(toObject, ['embeddings'], fromEmbeddings.map((item) => { + return contentEmbeddingFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['embeddings'], fromEmbeddings); + } + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(apiClient, fromObject) { + 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 generatedImageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(apiClient, fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(apiClient, fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + if (Array.isArray(fromGeneratedImages)) { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages.map((item) => { + return generatedImageFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages); + } + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(apiClient, fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function countTokensResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + 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 videoFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev$1(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromMldev$1(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromMldev$1(apiClient, fromResult)); + } + return toObject; +} +function partFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function candidateFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(apiClient, fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(apiClient, fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + 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) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + if (Array.isArray(fromCandidates)) { + setValueByPath(toObject, ['candidates'], fromCandidates.map((item) => { + return candidateFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['candidates'], fromCandidates); + } + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + 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 fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(apiClient, fromObject) { + 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); + } + return toObject; +} +function contentEmbeddingFromVertex(apiClient, fromObject) { + 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(apiClient, fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + if (Array.isArray(fromEmbeddings)) { + setValueByPath(toObject, ['embeddings'], fromEmbeddings.map((item) => { + return contentEmbeddingFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['embeddings'], fromEmbeddings); + } + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(apiClient, fromMetadata)); + } + return toObject; +} +function imageFromVertex(apiClient, fromObject) { + 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(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(apiClient, fromObject) { + 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 generatedImageFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(apiClient, 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(apiClient, fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + if (Array.isArray(fromGeneratedImages)) { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages.map((item) => { + return generatedImageFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages); + } + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(apiClient, fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function countTokensResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex$1(apiClient, 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(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex$1(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromVertex$1(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, ['response']); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromVertex$1(apiClient, fromResult)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Converters for live client. + */ +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig !== undefined && fromConfig !== null) { + setValueByPath(toObject, ['setup'], liveConnectConfigToMldev(apiClient, fromConfig)); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel !== undefined) { + setValueByPath(toObject, ['setup', 'model'], fromModel); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig !== undefined && fromConfig !== null) { + setValueByPath(toObject, ['setup'], liveConnectConfigToVertex(apiClient, fromConfig)); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel !== undefined) { + setValueByPath(toObject, ['setup', 'model'], fromModel); + } + return toObject; +} +function liveServerMessageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete !== undefined) { + setValueByPath(toObject, ['setupComplete'], fromSetupComplete); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent !== undefined && fromServerContent !== null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(apiClient, fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall !== undefined && fromToolCall !== null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(apiClient, fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation !== undefined && + fromToolCallCancellation !== null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(apiClient, fromToolCallCancellation)); + } + return toObject; +} +function liveServerMessageFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete !== undefined) { + setValueByPath(toObject, ['setupComplete'], fromSetupComplete); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent !== undefined && fromServerContent !== null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(apiClient, fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall !== undefined && fromToolCall !== null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(apiClient, fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation !== undefined && + fromToolCallCancellation !== null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(apiClient, fromToolCallCancellation)); + } + return toObject; +} +function liveConnectConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (fromGenerationConfig !== undefined) { + setValueByPath(toObject, ['generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities !== undefined) { + setValueByPath(toObject, ['generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig !== undefined) { + setValueByPath(toObject, ['generationConfig', 'speechConfig'], fromSpeechConfig); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) { + setValueByPath(toObject, ['systemInstruction'], contentToMldev(apiClient, fromSystemInstruction)); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (fromTools !== undefined && + fromTools !== null && + Array.isArray(fromTools)) { + setValueByPath(toObject, ['tools'], fromTools.map((item) => { + return toolToMldev(apiClient, item); + })); + } + return toObject; +} +function liveConnectConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (fromGenerationConfig !== undefined) { + setValueByPath(toObject, ['generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities !== undefined) { + setValueByPath(toObject, ['generationConfig', 'responseModalities'], fromResponseModalities); + } + else { + // Set default to AUDIO to align with MLDev API. + setValueByPath(toObject, ['generationConfig', 'responseModalities'], ['AUDIO']); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig !== undefined) { + setValueByPath(toObject, ['generationConfig', 'speechConfig'], fromSpeechConfig); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) { + setValueByPath(toObject, ['systemInstruction'], contentToVertex(apiClient, fromSystemInstruction)); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (fromTools !== undefined && + fromTools !== null && + Array.isArray(fromTools)) { + setValueByPath(toObject, ['tools'], fromTools.map((item) => { + return toolToVertex(apiClient, item); + })); + } + return toObject; +} +function liveServerContentFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn !== undefined && fromModelTurn !== null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev(apiClient, fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete !== undefined) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted !== undefined) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + return toObject; +} +function liveServerContentFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn !== undefined && fromModelTurn !== null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex(apiClient, fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete !== undefined) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted !== undefined) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + return toObject; +} +function functionCallFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId !== undefined) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs !== undefined) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName !== undefined) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function functionCallFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs !== undefined) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName !== undefined) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls !== undefined && + fromFunctionCalls !== null && + Array.isArray(fromFunctionCalls)) { + setValueByPath(toObject, ['functionCalls'], fromFunctionCalls.map((item) => { + return functionCallFromMldev(apiClient, item); + })); + } + return toObject; +} +function liveServerToolCallFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls !== undefined && + fromFunctionCalls !== null && + Array.isArray(fromFunctionCalls)) { + setValueByPath(toObject, ['functionCalls'], fromFunctionCalls.map((item) => { + return functionCallFromVertex(apiClient, item); + })); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds !== undefined) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds !== undefined) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} + +/** + * @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) { + let serverMessage; + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + if (apiClient.isVertexAI()) { + serverMessage = liveServerMessageFromVertex(apiClient, data); + } + else { + serverMessage = liveServerMessageFromMldev(apiClient, data); + } + 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; + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental + + @remarks + If using the Gemini API, Live is currently only supported behind API + version `v1alpha`. Ensure that the API version is set to `v1alpha` when + initializing the SDK if relying on the Gemini API. + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + 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; + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const headers = mapToHeaders(this.apiClient.getDefaultHeaders()); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateContent?key=${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; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(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(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(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + 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); + } + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } +} +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(apiClient, params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(apiClient, item)); + } + else { + contents = contents.map((item) => contentToMldev(apiClient, 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 }, + }; + } + tLiveClientRealtimeInput(apiClient, params) { + let clientMessage = {}; + if (!('media' in params) || !params.media) { + throw new Error(`Failed to convert realtime input "media", type: '${typeof params.media}'`); + } + // LiveClientRealtimeInput + clientMessage = { realtimeInput: { mediaChunks: [params.media] } }; + return clientMessage; + } + 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) { + if (params.media == null) { + throw new Error('Media is required.'); + } + const clientMessage = this.tLiveClientRealtimeInput(this.apiClient, 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 + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + 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 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI 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) => { + return await this.generateContentInternal(params); + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI 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) => { + return await this.generateContentStreamInternal(params); + }; + /** + * Generates an image based on a text description and configuration. + * + * @param model - The model to use. + * @param prompt - A text description of the image to generate. + * @param [config] - The config for image generation. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + 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, + }; + } + else { + response = { + generatedImages: generatedImages, + }; + } + return response; + }); + }; + } + async generateContentInternal(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(this.apiClient, 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b; + 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['config']; + 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, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_1, _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(apiClient, chunk); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _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(apiClient, chunk); + 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_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_2) throw e_2.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 embedContent(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * 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 ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new GenerateImagesResponse(); + 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; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(this.apiClient, 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(this.apiClient, 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; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * 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', + * 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.get({operation: operation}); + * } + * + * console.log(operation.result?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideos(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex$1(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev$1(this.apiClient, apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function getOperationParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(apiClient, 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); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromMldev(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromMldev(apiClient, fromResult)); + } + return toObject; +} +function videoFromVertex(apiClient, 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(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromVertex(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, ['response']); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromVertex(apiClient, fromResult)); + } + return toObject; +} + +/** + * @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 operation The Operation object returned by a previous API call. + * @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]; + var httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + return this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + } + else { + return this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(this.apiClient, params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = getOperationParametersToMldev(this.apiClient, params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(this.apiClient, apiResponse); + return resp; + }); + } + } + async fetchPredictVideosOperationInternal(params) { + var _a; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(this.apiClient, params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * 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 {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @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 { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error(`An API Key must be set when running in an unspecified environment.\n + ${crossError().message}`); + } + this.vertexai = (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross', + uploader: new CrossUploader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory()); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + } +} + +exports.Caches = Caches; +exports.Chat = Chat; +exports.Chats = Chats; +exports.ComputeTokensResponse = ComputeTokensResponse; +exports.CountTokensResponse = CountTokensResponse; +exports.CreateFileResponse = CreateFileResponse; +exports.DeleteCachedContentResponse = DeleteCachedContentResponse; +exports.DeleteFileResponse = DeleteFileResponse; +exports.EmbedContentResponse = EmbedContentResponse; +exports.Files = Files; +exports.FunctionResponse = FunctionResponse; +exports.GenerateContentResponse = GenerateContentResponse; +exports.GenerateContentResponsePromptFeedback = GenerateContentResponsePromptFeedback; +exports.GenerateContentResponseUsageMetadata = GenerateContentResponseUsageMetadata; +exports.GenerateImagesResponse = GenerateImagesResponse; +exports.GenerateVideosResponse = GenerateVideosResponse; +exports.GoogleGenAI = GoogleGenAI; +exports.HttpResponse = HttpResponse; +exports.ListCachedContentsResponse = ListCachedContentsResponse; +exports.ListFilesResponse = ListFilesResponse; +exports.Live = Live; +exports.LiveClientToolResponse = LiveClientToolResponse; +exports.LiveSendToolResponseParameters = LiveSendToolResponseParameters; +exports.Models = Models; +exports.Operations = Operations; +exports.Pager = Pager; +exports.ReplayResponse = ReplayResponse; +exports.Session = Session; +exports.createModelContent = createModelContent; +exports.createPartFromBase64 = createPartFromBase64; +exports.createPartFromCodeExecutionResult = createPartFromCodeExecutionResult; +exports.createPartFromExecutableCode = createPartFromExecutableCode; +exports.createPartFromFunctionCall = createPartFromFunctionCall; +exports.createPartFromFunctionResponse = createPartFromFunctionResponse; +exports.createPartFromText = createPartFromText; +exports.createPartFromUri = createPartFromUri; +exports.createUserContent = createUserContent; +//# sourceMappingURL=index.js.map diff --git a/node_modules/@google/genai/dist/index.js.map b/node_modules/@google/genai/dist/index.js.map new file mode 100644 index 0000000..3668b26 --- /dev/null +++ b/node_modules/@google/genai/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/_common.ts","../src/_transformers.ts","../src/converters/_caches_converters.ts","../src/pagers.ts","../src/types.ts","../src/caches.ts","../src/chats.ts","../src/_api_client.ts","../src/cross/_cross_error.ts","../src/cross/_cross_uploader.ts","../src/cross/_cross_websocket.ts","../src/converters/_files_converters.ts","../src/files.ts","../src/converters/_models_converters.ts","../src/converters/_live_converters.ts","../src/live.ts","../src/models.ts","../src/converters/_operations_converters.ts","../src/operations.ts","../src/web/_web_auth.ts","../src/client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {UploadFileConfig} from './types';\n\nexport class BaseModule {}\n\n// TODO (b/406332263): Move this to a place where it can be linked for doc.\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client';\nimport * as types from './types';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tPart(\n apiClient: ApiClient,\n origin?: types.PartUnion | null,\n): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(\n apiClient: ApiClient,\n origin?: types.PartListUnion | null,\n): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(apiClient, item as types.PartUnion)!);\n }\n return [tPart(apiClient, origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isUserPart(origin: unknown): boolean {\n if (origin === null || origin === undefined) {\n return false;\n }\n if (_isFunctionCallPart(origin)) {\n return false;\n }\n return true;\n}\n\nfunction _areUserParts(origin: types.PartListUnion[]): boolean {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n return false;\n }\n return origin.every(_isUserPart);\n}\n\nexport function tContent(\n apiClient: ApiClient,\n origin?: types.ContentUnion,\n): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // @ts-expect-error: _isContent is a utility function that checks if the\n // origin is a Content.\n return origin;\n }\n\n if (_isUserPart(origin)) {\n return {\n role: 'user',\n parts: tParts(apiClient, origin as types.PartListUnion)!,\n };\n } else {\n return {\n role: 'model',\n parts: tParts(apiClient, origin as types.PartListUnion)!,\n };\n }\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(apiClient, item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(apiClient, origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map(\n (item) => tContent(apiClient, item as types.ContentUnion)!,\n );\n }\n return [tContent(apiClient, origin as types.ContentUnion)!];\n}\n\nfunction _appendAccumulatedPartsAsContent(\n apiClient: ApiClient,\n result: types.Content[],\n accumulatedParts: types.PartUnion[],\n) {\n if (accumulatedParts.length === 0) {\n return;\n }\n if (_areUserParts(accumulatedParts)) {\n result.push({\n role: 'user',\n parts: tParts(apiClient, accumulatedParts),\n });\n } else {\n result.push({\n role: 'model',\n parts: tParts(apiClient, accumulatedParts),\n });\n }\n accumulatedParts.length = 0; // clear the array inplace\n}\n\nfunction _handleCurrentPart(\n apiClient: ApiClient,\n result: types.Content[],\n accumulatedParts: types.PartUnion[],\n currentPart: types.PartUnion,\n) {\n if (_isUserPart(currentPart) === _areUserParts(accumulatedParts)) {\n accumulatedParts.push(currentPart);\n } else {\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n accumulatedParts.length = 0;\n accumulatedParts.push(currentPart);\n }\n}\n\nexport function tContents(\n apiClient: ApiClient,\n origin?: types.ContentListUnion,\n): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n return [tContent(apiClient, origin)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n\n for (const content of origin) {\n if (_isContent(content)) {\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n // @ts-expect-error: content is a Content here\n result.push(content);\n } else if (\n typeof content === 'string' ||\n (typeof content === 'object' && !Array.isArray(content))\n ) {\n // @ts-expect-error: content is a part here\n _handleCurrentPart(apiClient, result, accumulatedParts, content);\n } else if (Array.isArray(content)) {\n // if there're consecutive user parts before the list,\n // convert to UserContent and append to result\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n result.push({\n role: 'user',\n parts: tParts(apiClient, content),\n });\n } else {\n throw new Error(`Unsupported content type: ${typeof content}`);\n }\n }\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n\n return result;\n}\n\nexport function processSchema(apiClient: ApiClient, schema: types.Schema) {\n if (!apiClient.isVertexAI()) {\n if ('default' in schema) {\n throw new Error(\n 'Default value is not supported in the response schema for the Gemini API.',\n );\n }\n }\n\n if ('anyOf' in schema) {\n if (schema['anyOf'] !== undefined) {\n for (const subSchema of schema['anyOf']) {\n processSchema(apiClient, subSchema);\n }\n }\n }\n\n if ('items' in schema) {\n if (schema['items'] !== undefined) {\n processSchema(apiClient, schema['items']);\n }\n }\n\n if ('properties' in schema) {\n if (schema['properties'] !== undefined) {\n for (const subSchema of Object.values(schema['properties'])) {\n processSchema(apiClient, subSchema);\n }\n }\n }\n}\n\nexport function tSchema(\n apiClient: ApiClient,\n schema: types.Schema,\n): types.Schema {\n processSchema(apiClient, schema);\n return schema;\n}\n\nexport function tSpeechConfig(\n apiClient: ApiClient,\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object' && 'voiceConfig' in speechConfig) {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tTool(apiClient: ApiClient, tool: types.Tool): types.Tool {\n return tool;\n}\n\nexport function tTools(\n apiClient: ApiClient,\n tool: types.Tool[] | unknown,\n): types.Tool[] {\n if (!Array.isArray(tool)) {\n throw new Error('tool is required and must be an array of Tools');\n }\n return tool;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(\n apiClient: ApiClient,\n status: string | unknown,\n): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(\n apiClient: ApiClient,\n fromImageBytes: string | unknown,\n): string {\n if (typeof fromImageBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromImageBytes;\n}\nexport function tFileName(\n apiClient: ApiClient,\n fromName: string | unknown,\n): string {\n if (typeof fromName !== 'string') {\n throw new Error('fromName must be a string');\n }\n // Remove the files/ prefx for MLdev urls to get the actual name of the file.\n if (fromName.startsWith('files/')) {\n return fromName.split('files/')[1];\n }\n return fromName;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function partToMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['videoMetadata']) !== undefined) {\n throw new Error('videoMetadata parameter is not supported in Gemini API.');\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['example']) !== undefined) {\n throw new Error('example parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['pattern']) !== undefined) {\n throw new Error('pattern parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['default']) !== undefined) {\n throw new Error('default parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxLength']) !== undefined) {\n throw new Error('maxLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minLength']) !== undefined) {\n throw new Error('minLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minProperties']) !== undefined) {\n throw new Error('minProperties parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxProperties']) !== undefined) {\n throw new Error('maxProperties parameter is not supported in Gemini API.');\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['response']) !== undefined) {\n throw new Error('response parameter is not supported in Gemini API.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToMldev(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToMldev());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(apiClient, fromToolConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partToVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n schemaToVertex(apiClient, fromResponse),\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToVertex(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToVertex());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(apiClient, fromToolConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n apiClient: ApiClient,\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n if (Array.isArray(fromCachedContents)) {\n common.setValueByPath(\n toObject,\n ['cachedContents'],\n fromCachedContents.map((item) => {\n return cachedContentFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['cachedContents'], fromCachedContents);\n }\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n apiClient: ApiClient,\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n if (Array.isArray(fromCachedContents)) {\n common.setValueByPath(\n toObject,\n ['cachedContents'],\n fromCachedContents.map((item) => {\n return cachedContentFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['cachedContents'], fromCachedContents);\n }\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nexport enum Outcome {\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n OUTCOME_OK = 'OUTCOME_OK',\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\nexport enum Language {\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n PYTHON = 'PYTHON',\n}\n\nexport enum Type {\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n STRING = 'STRING',\n NUMBER = 'NUMBER',\n INTEGER = 'INTEGER',\n BOOLEAN = 'BOOLEAN',\n ARRAY = 'ARRAY',\n OBJECT = 'OBJECT',\n}\n\nexport enum HarmCategory {\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n}\n\nexport enum HarmBlockMethod {\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n SEVERITY = 'SEVERITY',\n PROBABILITY = 'PROBABILITY',\n}\n\nexport enum HarmBlockThreshold {\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n OFF = 'OFF',\n}\n\nexport enum Mode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\nexport enum FinishReason {\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n STOP = 'STOP',\n MAX_TOKENS = 'MAX_TOKENS',\n SAFETY = 'SAFETY',\n RECITATION = 'RECITATION',\n OTHER = 'OTHER',\n BLOCKLIST = 'BLOCKLIST',\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n SPII = 'SPII',\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\nexport enum HarmProbability {\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n NEGLIGIBLE = 'NEGLIGIBLE',\n LOW = 'LOW',\n MEDIUM = 'MEDIUM',\n HIGH = 'HIGH',\n}\n\nexport enum HarmSeverity {\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\nexport enum BlockedReason {\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n SAFETY = 'SAFETY',\n OTHER = 'OTHER',\n BLOCKLIST = 'BLOCKLIST',\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n}\n\nexport enum Modality {\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n TEXT = 'TEXT',\n IMAGE = 'IMAGE',\n AUDIO = 'AUDIO',\n}\n\nexport enum State {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n ACTIVE = 'ACTIVE',\n ERROR = 'ERROR',\n}\n\nexport enum DynamicRetrievalConfigMode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\nexport enum FunctionCallingConfigMode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n AUTO = 'AUTO',\n ANY = 'ANY',\n NONE = 'NONE',\n}\n\nexport enum MediaResolution {\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\nexport enum PersonGeneration {\n DONT_ALLOW = 'DONT_ALLOW',\n ALLOW_ADULT = 'ALLOW_ADULT',\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\nexport enum ImagePromptLanguage {\n auto = 'auto',\n en = 'en',\n ja = 'ja',\n ko = 'ko',\n hi = 'hi',\n}\n\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\nexport enum MediaModality {\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n TEXT = 'TEXT',\n IMAGE = 'IMAGE',\n VIDEO = 'VIDEO',\n AUDIO = 'AUDIO',\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Metadata describes the input video content. */\nexport declare interface VideoMetadata {\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [FunctionDeclaration] tool and [FunctionCallingConfig] mode is set to [Mode.CODE]. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. Required. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** The id of the function call this response is for. Populated by the client\n to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Required. Raw bytes. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n left blank or unset. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n}\n\n/** Schema that defines the format of input and output data.\n\n Represents a select subset of an OpenAPI 3.0 schema object.\n */\nexport declare interface Schema {\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Describes the output from the function in the OpenAPI JSON Schema\n Object format. */\n response?: Schema;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. This field is only used by the Gemini Developer API services. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use.\n */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. e.g. 'gemini-1.5-pro-001'. */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response media type of the generated candidate text.\n */\n responseMimeType?: string;\n /** Schema that the generated candidate text must adhere to.\n */\n responseSchema?: SchemaUnion;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. This list must have the same size as the grounding_chunk_indices. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** Identifier for each response.\n */\n responseId?: string;\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `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.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport /** Optional parameters for the embed_content method. */\ndeclare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images.\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** Whether to use the prompt rewriting logic.\n */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both.\n */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories.\n */\n categories?: string[];\n /** List of scores of each categories.\n */\n scores?: number[];\n /** Internal use only.\n */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data.\n */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response.\n */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content.\n */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled.\n */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** List of generated images.\n */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True.\n */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional. Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 1280x720, 1920x1080 are supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation progress. */\n pubsubTopic?: string;\n /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** Class that represents the parameters for generating an image. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos. Optional for image to video use cases. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt is provided. */\n image?: Image;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes. */\n videoBytes?: string;\n /** Video encoding, for example \"video/mp4\". */\n mimeType?: string;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** A video generation operation. */\nexport declare interface GenerateVideosOperation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The normal response of the operation in case of success. */\n response?: Record;\n /** The generated videos. */\n result?: GenerateVideosResponse;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-1.5-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n onopen?: (() => void) | null;\n onmessage: (e: LiveServerMessage) => void;\n onerror?: ((e: ErrorEvent) => void) | null;\n onclose?: ((e: CloseEvent) => void) | null;\n}\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression if the ``output_mime_type`` is\n ``image/jpeg``. */\n outputCompressionQuality?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport declare interface RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport declare interface MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport declare interface ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport declare interface StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport declare interface SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n}\n\n/** Sent in response to a `LiveGenerateContentSetup` message from the client. */\nexport declare interface LiveServerSetupComplete {}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Response message for API call. */\nexport declare interface LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n\nThe following fields are supported:\n- `response_logprobs`\n- `response_mime_type`\n- `logprobs`\n- `response_schema`\n- `stop_sequence`\n- `routing_config`\n- `audio_timestamp`\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: Content;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** User input that is sent in real time.\n\n This is different from `ClientContentUpdate` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `ClientContentUpdate` and the `RealtimeUpdate`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: Content;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-1.5-pro', etc. See gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media: Blob;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters {\n /** The operation to be retrieved. */\n operation: GenerateVideosOperation;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = ContentUnion[] | ContentUnion;\n\nexport type SchemaUnion = Schema;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolListUnion = Tool[];\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_caches_converters';\nimport {PagedItem, Pager} from './pagers';\nimport * as types from './types';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference] (https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference] (https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-1.5-flash',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: 'gemini-1.5-flash'});\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: 'gemini-1.5-flash'});\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromVertex();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromMldev();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: 'gemini-1.5-flash',\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listCachedContentsResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listCachedContentsResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client';\nimport * as t from './_transformers';\nimport {Models} from './models';\nimport * as types from './types';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\n if (content.parts === undefined || content.parts.length === 0) {\n return false;\n }\n for (const part of content.parts) {\n if (part === undefined || Object.keys(part).length === 0) {\n return false;\n }\n if (part.text !== undefined && part.text === '') {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @remarks\n * Expects the history to start with a user turn and then alternate between\n * user and model turns.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n if (history[0].role !== 'user') {\n throw new Error('History must start with a user turn.');\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n let userInput = comprehensiveHistory[0];\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n userInput = comprehensiveHistory[i];\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(userInput);\n curatedHistory.push(...modelOutput);\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n params.history,\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(this.apiClient, params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(inputContent, modelOutput);\n return;\n })();\n await this.sendPromise;\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(this.apiClient, params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = streamResponse.then(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n return curated ? extractCuratedHistory(this.history) : this.history;\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role === 'model')\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n this.history.push(userInput);\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth';\nimport * as common from './_common';\nimport {Uploader} from './_uploader';\nimport {File, HttpOptions, HttpResponse, UploadFileConfig} from './types';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst USER_AGENT_HEADER = 'User-Agent';\nconst GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '0.7.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Client errors raised by the GenAI API.\n */\nexport class ClientError extends Error {\n constructor(message: string, stackTrace?: string) {\n if (stackTrace) {\n super(message, {cause: stackTrace});\n } else {\n super(message, {cause: new Error().stack});\n }\n this.message = message;\n this.name = 'ClientError';\n }\n}\n\n/**\n * Server errors raised by the GenAI API.\n */\nexport class ServerError extends Error {\n constructor(message: string, stackTrace?: string) {\n if (stackTrace) {\n super(message, {cause: stackTrace});\n } else {\n super(message, {cause: new Error().stack});\n }\n this.message = message;\n this.name = 'ServerError';\n }\n}\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n // Assume that proj/api key validation occurs before they are passed in.\n if (this.getProject() || this.getLocation()) {\n initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n this.clientOptions.apiKey = undefined; // unset API key.\n } else {\n initHttpOptions.baseUrl = `https://aiplatform.googleapis.com/`;\n this.clientOptions.project = undefined; // unset project.\n this.clientOptions.location = undefined; // unset location.\n }\n } else {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(path: string, httpOptions: HttpOptions): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (\n this.clientOptions.vertexai &&\n !this.clientOptions.apiKey &&\n !path.startsWith('projects/')\n ) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const url = this.constructUrl(request.path, patchedHttpOptions);\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const url = this.constructUrl(request.path, patchedHttpOptions);\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n ): Promise {\n if (httpOptions && httpOptions.timeout && httpOptions.timeout > 0) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n setTimeout(() => abortController.abort(), httpOptions.timeout);\n requestInit.signal = signal;\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value);\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const chunkData = JSON.parse(processedChunkString);\n yield chunkData;\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new ServerError('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n const statusText: string = response.statusText;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: 'exception parsing response',\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = `got status: ${status} ${statusText}. ${JSON.stringify(\n errorBody,\n )}`;\n if (status >= 400 && status < 500) {\n const clientError = new ClientError(errorMessage);\n throw clientError;\n } else if (status >= 500 && status < 600) {\n const serverError = new ServerError(errorMessage);\n throw serverError;\n }\n throw new Error(errorMessage);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function crossError(): Error {\n // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports\n return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either:\n\n*Enabling conditional exports for your project [recommended]*\n\n*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'.\n`);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client';\nimport {FileStat, Uploader} from '../_uploader';\nimport {File, HttpResponse} from '../types';\n\nimport {crossError} from './_cross_error';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.['x-goog-upload-status'] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.['x-goog-upload-status'] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n WebSocketCallbacks,\n WebSocketFactory,\n WebSocket as Ws,\n} from '../_websocket';\nimport {crossError} from './_cross_error';\n\n// TODO((b/401271082): re-enable lint once CrossWebSocketFactory is implemented.\n/* eslint-disable @typescript-eslint/no-unused-vars */\nexport class CrossWebSocketFactory implements WebSocketFactory {\n create(\n url: string,\n headers: Record,\n callbacks: WebSocketCallbacks,\n ): Ws {\n throw crossError();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function listFilesConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n apiClient: ApiClient,\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(\n apiClient: ApiClient,\n fromObject: types.File,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(\n toObject,\n ['error'],\n fileStatusToMldev(apiClient, fromError),\n );\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(apiClient, fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'file'],\n t.tFileName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'file'],\n t.tFileName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n apiClient: ApiClient,\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(\n apiClient: ApiClient,\n fromObject: types.File,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(\n toObject,\n ['error'],\n fileStatusFromMldev(apiClient, fromError),\n );\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n if (Array.isArray(fromFiles)) {\n common.setValueByPath(\n toObject,\n ['files'],\n fromFiles.map((item) => {\n return fileFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['files'], fromFiles);\n }\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromHttpHeaders = common.getValueByPath(fromObject, ['httpHeaders']);\n if (fromHttpHeaders != null) {\n common.setValueByPath(toObject, ['httpHeaders'], fromHttpHeaders);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_files_converters';\nimport {PagedItem, Pager} from './pagers';\nimport * as types from './types';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `common.UploadFileParameters` interface.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: common.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(this.apiClient, response);\n return file as types.File;\n });\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(this.apiClient, apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteFileResponseFromMldev();\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function partToMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['videoMetadata']) !== undefined) {\n throw new Error('videoMetadata parameter is not supported in Gemini API.');\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['example']) !== undefined) {\n throw new Error('example parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['pattern']) !== undefined) {\n throw new Error('pattern parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['default']) !== undefined) {\n throw new Error('default parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxLength']) !== undefined) {\n throw new Error('maxLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minLength']) !== undefined) {\n throw new Error('minLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minProperties']) !== undefined) {\n throw new Error('minProperties parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxProperties']) !== undefined) {\n throw new Error('maxProperties parameter is not supported in Gemini API.');\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n apiClient: ApiClient,\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['response']) !== undefined) {\n throw new Error('response parameter is not supported in Gemini API.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToMldev(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToMldev());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(apiClient, fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(apiClient, fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(apiClient, t.tSchema(apiClient, fromResponseSchema)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n if (Array.isArray(fromSafetySettings)) {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings.map((item) => {\n return safetySettingToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings,\n );\n }\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(\n apiClient,\n t.tTools(apiClient, fromTools).map((item) => {\n return toolToMldev(apiClient, t.tTool(apiClient, item));\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(apiClient, fromTools),\n );\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(apiClient, fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(\n apiClient,\n t.tSpeechConfig(apiClient, fromSpeechConfig),\n ),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(apiClient, fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(apiClient, fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n if (common.getValueByPath(fromObject, ['resolution']) !== undefined) {\n throw new Error('resolution parameter is not supported in Gemini API.');\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(apiClient, fromImage),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partToVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n apiClient: ApiClient,\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n schemaToVertex(apiClient, fromResponse),\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToVertex(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToVertex());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(apiClient, fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(apiClient, fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(apiClient, t.tSchema(apiClient, fromResponseSchema)),\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n if (Array.isArray(fromSafetySettings)) {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings.map((item) => {\n return safetySettingToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings,\n );\n }\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(\n apiClient,\n t.tTools(apiClient, fromTools).map((item) => {\n return toolToVertex(apiClient, t.tTool(apiClient, item));\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(apiClient, fromTools),\n );\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(apiClient, fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(\n apiClient,\n t.tSpeechConfig(apiClient, fromSpeechConfig),\n ),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(apiClient, fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(apiClient, fromImage),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partFromMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n apiClient: ApiClient,\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n apiClient: ApiClient,\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromMldev(apiClient, fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(apiClient, fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n if (Array.isArray(fromCandidates)) {\n common.setValueByPath(\n toObject,\n ['candidates'],\n fromCandidates.map((item) => {\n return candidateFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['candidates'], fromCandidates);\n }\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n apiClient: ApiClient,\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n if (Array.isArray(fromEmbeddings)) {\n common.setValueByPath(\n toObject,\n ['embeddings'],\n fromEmbeddings.map((item) => {\n return contentEmbeddingFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['embeddings'], fromEmbeddings);\n }\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['imageBytes'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n apiClient: ApiClient,\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['image'],\n imageFromMldev(apiClient, fromImage),\n );\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(apiClient, fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n if (Array.isArray(fromGeneratedImages)) {\n common.setValueByPath(\n toObject,\n ['generatedImages'],\n fromGeneratedImages.map((item) => {\n return generatedImageFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedImages'], fromGeneratedImages);\n }\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(apiClient, fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromMldev(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromMldev(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n apiClient: ApiClient,\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n apiClient: ApiClient,\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(apiClient, fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(apiClient, fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n if (Array.isArray(fromCandidates)) {\n common.setValueByPath(\n toObject,\n ['candidates'],\n fromCandidates.map((item) => {\n return candidateFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['candidates'], fromCandidates);\n }\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n apiClient: ApiClient,\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n apiClient: ApiClient,\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(apiClient, fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n if (Array.isArray(fromEmbeddings)) {\n common.setValueByPath(\n toObject,\n ['embeddings'],\n fromEmbeddings.map((item) => {\n return contentEmbeddingFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['embeddings'], fromEmbeddings);\n }\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(apiClient, fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['imageBytes'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n apiClient: ApiClient,\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['image'],\n imageFromVertex(apiClient, fromImage),\n );\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(apiClient, fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n if (Array.isArray(fromGeneratedImages)) {\n common.setValueByPath(\n toObject,\n ['generatedImages'],\n fromGeneratedImages.map((item) => {\n return generatedImageFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedImages'], fromGeneratedImages);\n }\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(apiClient, fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromVertex(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, ['response']);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromVertex(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as types from '../types';\nimport {\n contentFromMldev,\n contentFromVertex,\n contentToMldev,\n contentToVertex,\n toolToMldev,\n toolToVertex,\n} from './_models_converters';\n\n/**\n * Converters for live client.\n */\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): types.LiveClientMessage {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig !== undefined && fromConfig !== null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveConnectConfigToMldev(apiClient, fromConfig),\n );\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel !== undefined) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): types.LiveClientMessage {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig !== undefined && fromConfig !== null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveConnectConfigToVertex(apiClient, fromConfig),\n );\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel !== undefined) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerMessage,\n): types.LiveServerMessage {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete !== undefined) {\n common.setValueByPath(toObject, ['setupComplete'], fromSetupComplete);\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent !== undefined && fromServerContent !== null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(apiClient, fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall !== undefined && fromToolCall !== null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(apiClient, fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (\n fromToolCallCancellation !== undefined &&\n fromToolCallCancellation !== null\n ) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(\n apiClient,\n fromToolCallCancellation,\n ),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerMessage,\n): types.LiveServerMessage {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete !== undefined) {\n common.setValueByPath(toObject, ['setupComplete'], fromSetupComplete);\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent !== undefined && fromServerContent !== null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(apiClient, fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall !== undefined && fromToolCall !== null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(apiClient, fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (\n fromToolCallCancellation !== undefined &&\n fromToolCallCancellation !== null\n ) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(\n apiClient,\n fromToolCallCancellation,\n ),\n );\n }\n\n return toObject;\n}\n\nfunction liveConnectConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConfig,\n): types.LiveClientSetup {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig !== undefined) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'speechConfig'],\n fromSpeechConfig,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(apiClient, fromSystemInstruction),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (\n fromTools !== undefined &&\n fromTools !== null &&\n Array.isArray(fromTools)\n ) {\n common.setValueByPath(\n toObject,\n ['tools'],\n fromTools.map((item: types.Tool) => {\n return toolToMldev(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveConnectConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConfig,\n): types.LiveClientSetup {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig !== undefined) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n } else {\n // Set default to AUDIO to align with MLDev API.\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n ['AUDIO'],\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'speechConfig'],\n fromSpeechConfig,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(apiClient, fromSystemInstruction),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (\n fromTools !== undefined &&\n fromTools !== null &&\n Array.isArray(fromTools)\n ) {\n common.setValueByPath(\n toObject,\n ['tools'],\n fromTools.map((item: types.Tool) => {\n return toolToVertex(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerContentFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerContent,\n): types.LiveServerContent {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn !== undefined && fromModelTurn !== null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(apiClient, fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete !== undefined) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted !== undefined) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n return toObject;\n}\n\nfunction liveServerContentFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerContent,\n): types.LiveServerContent {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn !== undefined && fromModelTurn !== null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(apiClient, fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete !== undefined) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted !== undefined) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n return toObject;\n}\n\nfunction functionCallFromMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCall,\n): types.FunctionCall {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId !== undefined) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs !== undefined) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName !== undefined) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nfunction functionCallFromVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCall,\n): types.FunctionCall {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs !== undefined) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName !== undefined) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCall,\n): types.LiveServerToolCall {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (\n fromFunctionCalls !== undefined &&\n fromFunctionCalls !== null &&\n Array.isArray(fromFunctionCalls)\n ) {\n common.setValueByPath(\n toObject,\n ['functionCalls'],\n fromFunctionCalls.map((item: types.FunctionCall) => {\n return functionCallFromMldev(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCall,\n): types.LiveServerToolCall {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (\n fromFunctionCalls !== undefined &&\n fromFunctionCalls !== null &&\n Array.isArray(fromFunctionCalls)\n ) {\n common.setValueByPath(\n toObject,\n ['functionCalls'],\n fromFunctionCalls.map((item: types.FunctionCall) => {\n return functionCallFromVertex(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallCancellationFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCallCancellation,\n): types.LiveServerToolCallCancellation {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds !== undefined) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallCancellationFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCallCancellation,\n): types.LiveServerToolCallCancellation {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds !== undefined) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client';\nimport {Auth} from './_auth';\nimport * as t from './_transformers';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket';\nimport * as converters from './converters/_live_converters';\nimport {contentToMldev, contentToVertex} from './converters/_models_converters';\nimport * as types from './types';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n let serverMessage: types.LiveServerMessage;\n let data: types.LiveServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveServerMessage;\n }\n if (apiClient.isVertexAI()) {\n serverMessage = converters.liveServerMessageFromVertex(apiClient, data);\n } else {\n serverMessage = converters.liveServerMessageFromMldev(apiClient, data);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental\n\n @remarks\n If using the Gemini API, Live is currently only supported behind API\n version `v1alpha`. Ensure that the API version is set to `v1alpha` when\n initializing the SDK if relying on the Gemini API.\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n const session = await ai.live.connect({\n model: 'gemini-2.0-flash-exp',\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateContent?key=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: types.LiveClientMessage = {};\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(\n apiClient,\n params.turns as types.ContentListUnion,\n );\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(apiClient, item));\n } else {\n contents = contents.map((item) => contentToMldev(apiClient, item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClientRealtimeInput(\n apiClient: ApiClient,\n params: types.LiveSendRealtimeInputParameters,\n ): types.LiveClientMessage {\n let clientMessage: types.LiveClientMessage = {};\n if (!('media' in params) || !params.media) {\n throw new Error(\n `Failed to convert realtime input \"media\", type: '${typeof params.media}'`,\n );\n }\n\n // LiveClientRealtimeInput\n clientMessage = {realtimeInput: {mediaChunks: [params.media]}};\n return clientMessage;\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n if (params.media == null) {\n throw new Error('Media is required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClientRealtimeInput(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n const session = await ai.live.connect({\n model: 'gemini-2.0-flash-exp',\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_models_converters';\nimport * as types from './types';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n return await this.generateContentInternal(params);\n };\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n return await this.generateContentStreamInternal(params);\n };\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param model - The model to use.\n * @param prompt - A text description of the image to generate.\n * @param [config] - The config for image generation.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n };\n }\n return response;\n });\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n apiClient,\n chunk,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n apiClient,\n chunk,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.get({operation: operation});\n * }\n *\n * console.log(operation.result?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n async generateVideos(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function getOperationParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromMldev(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromMldev(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromVertex(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, ['response']);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromVertex(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_operations_converters';\nimport * as types from './types';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param operation The Operation object returned by a previous API call.\n * @return The updated Operation object, with the latest status or result.\n */\n async get(\n parameters: types.OperationGetParameters,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n var httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n return this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n } else {\n return this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n const body = converters.getOperationParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from '../_auth';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\n// TODO(b/395122533): We need a secure client side authentication mechanism.\nexport class WebAuth implements Auth {\n constructor(private readonly apiKey: string) {}\n\n async addAuthHeaders(headers: Headers): Promise {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuthOptions} from 'google-auth-library';\n\nimport {ApiClient} from './_api_client';\nimport {Caches} from './caches';\nimport {Chats} from './chats';\nimport {crossError} from './cross/_cross_error';\nimport {CrossUploader} from './cross/_cross_uploader';\nimport {CrossWebSocketFactory} from './cross/_cross_websocket';\nimport {Files} from './files';\nimport {Live} from './live';\nimport {Models} from './models';\nimport {Operations} from './operations';\nimport {HttpOptions} from './types';\nimport {WebAuth} from './web/_web_auth';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * Google Gen AI SDK's configuration options.\n *\n * See {@link GoogleGenAI} for usage samples.\n */\nexport interface GoogleGenAIOptions {\n /**\n * Optional. Determines whether to use the Vertex AI or the Gemini API.\n *\n * @remarks\n * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used.\n * When false, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} will be used.\n *\n * If unset, default SDK behavior is to use the Gemini API service.\n */\n vertexai?: boolean;\n /**\n * Optional. The Google Cloud project ID for Vertex AI clients.\n *\n * @remarks\n * Only supported on Node runtimes, ignored on browser runtimes.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project region for Vertex AI clients.\n *\n * @remarks\n * Only supported on Node runtimes, ignored on browser runtimes.\n *\n */\n location?: string;\n /**\n * The API Key, required for Gemini API clients.\n *\n * @remarks\n * Required on browser runtimes.\n */\n apiKey?: string;\n /**\n * Optional. The API version to use.\n *\n * @remarks\n * If unset, the default API version will be used.\n */\n apiVersion?: string;\n /**\n * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients.\n *\n * @remarks\n * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}.\n *\n * Only supported on Node runtimes, ignored on browser runtimes.\n *\n */\n googleAuthOptions?: GoogleAuthOptions;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n}\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API}\n * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set,\n * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n\n constructor(options: GoogleGenAIOptions) {\n if (options.apiKey == null) {\n throw new Error(\n `An API Key must be set when running in an unspecified environment.\\n + ${crossError().message}`,\n );\n }\n this.vertexai = options.vertexai ?? false;\n this.apiKey = options.apiKey;\n this.apiVersion = options.apiVersion;\n const auth = new WebAuth(this.apiKey);\n this.apiClient = new ApiClient({\n auth: auth,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross',\n uploader: new CrossUploader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory());\n this.chats = new Chats(this.models, this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n }\n}\n"],"names":["partToMldev","common.getValueByPath","common.setValueByPath","contentToMldev","functionDeclarationToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","toolToMldev","functionCallingConfigToMldev","toolConfigToMldev","t.tContents","t.tContent","t.tCachesModel","t.tCachedContentName","partToVertex","contentToVertex","schemaToVertex","functionDeclarationToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","toolToVertex","functionCallingConfigToVertex","toolConfigToVertex","PagedItem","Outcome","Language","Type","HarmCategory","HarmBlockMethod","HarmBlockThreshold","Mode","FinishReason","HarmProbability","HarmSeverity","BlockedReason","Modality","State","DynamicRetrievalConfigMode","FunctionCallingConfigMode","MediaResolution","SafetyFilterLevel","PersonGeneration","ImagePromptLanguage","FileState","FileSource","MaskReferenceMode","ControlReferenceType","SubjectReferenceType","MediaModality","converters.createCachedContentParametersToVertex","common.formatMap","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","t.tSchema","t.tTools","t.tTool","t.tSpeechConfig","t.tModel","t.tContentsForEmbed","t.tBytes","videoFromMldev","generatedVideoFromMldev","generateVideosResponseFromMldev","generateVideosOperationFromMldev","videoFromVertex","generatedVideoFromVertex","generateVideosResponseFromVertex","generateVideosOperationFromVertex","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","types.GenerateContentResponse","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex"],"mappings":";;AAAA;;;;AAIG;MAIU,UAAU,CAAA;AAAG;AAWV,SAAA,SAAS,CACvB,cAAsB,EACtB,QAAiC,EAAA;;IAGjC,MAAM,KAAK,GAAG,cAAc;;IAG5B,OAAO,cAAc,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,GAAG,KAAI;AAClD,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE;AACvD,YAAA,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC;;AAE3B,YAAA,OAAO,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;AAClE;AAAM,aAAA;;AAEL,YAAA,MAAM,IAAI,KAAK,CAAC,QAAQ,GAAG,CAAA,wBAAA,CAA0B,CAAC;AACvD;AACH,KAAC,CAAC;AACJ;SAEgB,cAAc,CAC5B,IAA6B,EAC7B,IAAc,EACd,KAAc,EAAA;AAEd,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AACxC,QAAA,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC;AAEnB,QAAA,IAAI,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;YACtB,MAAM,OAAO,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;AAChC,YAAA,IAAI,EAAE,OAAO,IAAI,IAAI,CAAC,EAAE;AACtB,g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CAAC,QAAQ;YACvB,WAAW,EAAE,OAAO,CAAC,WAAW;YAChC,cAAc,EAAE,qBAAqB,GAAG,OAAO;YAC/C,QAAQ,EAAE,IAAI,aAAa,EAAE;AAC9B,SAAA,CAAC;QACF,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;AACxC,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,qBAAqB,EAAE,CAAC;AACvE,QAAA,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC;QACnD,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QACxC,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC;QACtC,IAAI,CAAC,UAAU,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC;;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@google/genai/dist/index.mjs b/node_modules/@google/genai/dist/index.mjs new file mode 100644 index 0000000..7252e03 --- /dev/null +++ b/node_modules/@google/genai/dist/index.mjs @@ -0,0 +1,7852 @@ +/** + * @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 { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + 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 undefined; + } + 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 undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @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 (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 tPart(apiClient, 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(apiClient, 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(apiClient, item)); + } + return [tPart(apiClient, 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 _isUserPart(origin) { + if (origin === null || origin === undefined) { + return false; + } + if (_isFunctionCallPart(origin)) { + return false; + } + return true; +} +function _areUserParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + return false; + } + return origin.every(_isUserPart); +} +function tContent(apiClient, origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // @ts-expect-error: _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + if (_isUserPart(origin)) { + return { + role: 'user', + parts: tParts(apiClient, origin), + }; + } + else { + return { + role: 'model', + parts: tParts(apiClient, origin), + }; + } +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(apiClient, 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(apiClient, 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(apiClient, item)); + } + return [tContent(apiClient, origin)]; +} +function _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts) { + if (accumulatedParts.length === 0) { + return; + } + if (_areUserParts(accumulatedParts)) { + result.push({ + role: 'user', + parts: tParts(apiClient, accumulatedParts), + }); + } + else { + result.push({ + role: 'model', + parts: tParts(apiClient, accumulatedParts), + }); + } + accumulatedParts.length = 0; // clear the array inplace +} +function _handleCurrentPart(apiClient, result, accumulatedParts, currentPart) { + if (_isUserPart(currentPart) === _areUserParts(accumulatedParts)) { + accumulatedParts.push(currentPart); + } + else { + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + accumulatedParts.length = 0; + accumulatedParts.push(currentPart); + } +} +function tContents(apiClient, origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + return [tContent(apiClient, origin)]; + } + const result = []; + const accumulatedParts = []; + for (const content of origin) { + if (_isContent(content)) { + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + // @ts-expect-error: content is a Content here + result.push(content); + } + else if (typeof content === 'string' || + (typeof content === 'object' && !Array.isArray(content))) { + // @ts-expect-error: content is a part here + _handleCurrentPart(apiClient, result, accumulatedParts, content); + } + else if (Array.isArray(content)) { + // if there're consecutive user parts before the list, + // convert to UserContent and append to result + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + result.push({ + role: 'user', + parts: tParts(apiClient, content), + }); + } + else { + throw new Error(`Unsupported content type: ${typeof content}`); + } + } + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + return result; +} +function processSchema(apiClient, schema) { + if (!apiClient.isVertexAI()) { + if ('default' in schema) { + throw new Error('Default value is not supported in the response schema for the Gemini API.'); + } + } + if ('anyOf' in schema) { + if (schema['anyOf'] !== undefined) { + for (const subSchema of schema['anyOf']) { + processSchema(apiClient, subSchema); + } + } + } + if ('items' in schema) { + if (schema['items'] !== undefined) { + processSchema(apiClient, schema['items']); + } + } + if ('properties' in schema) { + if (schema['properties'] !== undefined) { + for (const subSchema of Object.values(schema['properties'])) { + processSchema(apiClient, subSchema); + } + } + } +} +function tSchema(apiClient, schema) { + processSchema(apiClient, schema); + return schema; +} +function tSpeechConfig(apiClient, speechConfig) { + if (typeof speechConfig === 'object' && 'voiceConfig' in speechConfig) { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tTool(apiClient, tool) { + return tool; +} +function tTools(apiClient, tool) { + if (!Array.isArray(tool)) { + throw new Error('tool is required and must be an array of Tools'); + } + return tool; +} +/** + * 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 tBytes(apiClient, fromImageBytes) { + if (typeof fromImageBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromImageBytes; +} +function tFileName(apiClient, fromName) { + if (typeof fromName !== 'string') { + throw new Error('fromName must be a string'); + } + // Remove the files/ prefx for MLdev urls to get the actual name of the file. + if (fromName.startsWith('files/')) { + return fromName.split('files/')[1]; + } + return fromName; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function partToMldev$1(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['videoMetadata']) !== undefined) { + throw new Error('videoMetadata parameter is not supported in Gemini API.'); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$1(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['response']) !== undefined) { + throw new Error('response parameter is not supported in Gemini API.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToMldev$1() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(apiClient, 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) { + if (Array.isArray(fromContents)) { + setValueByPath(parentObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev$1(apiClient, item); + }))); + } + else { + setValueByPath(parentObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(apiClient, fromToolConfig)); + } + 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) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(apiClient, 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) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(apiClient, 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(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function functionDeclarationToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], schemaToVertex$1(apiClient, fromResponse)); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToVertex$1() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(apiClient, 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) { + if (Array.isArray(fromContents)) { + setValueByPath(parentObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex$1(apiClient, item); + }))); + } + else { + setValueByPath(parentObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$1(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(apiClient, fromToolConfig)); + } + 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) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(apiClient, 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 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) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(apiClient, 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 listCachedContentsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(apiClient, 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 fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + if (Array.isArray(fromCachedContents)) { + setValueByPath(toObject, ['cachedContents'], fromCachedContents.map((item) => { + return cachedContentFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['cachedContents'], fromCachedContents); + } + } + return toObject; +} +function cachedContentFromVertex(apiClient, 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 fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + if (Array.isArray(fromCachedContents)) { + setValueByPath(toObject, ['cachedContents'], fromCachedContents.map((item) => { + return cachedContentFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['cachedContents'], fromCachedContents); + } + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Pagers for the GenAI List APIs. + */ +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 || (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.idxInternal = 0; + let requestParams = { config: {} }; + if (!params) { + 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 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 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +var Outcome; +(function (Outcome) { + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(Outcome || (Outcome = {})); +var Language; +(function (Language) { + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +var Type; +(function (Type) { + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + Type["STRING"] = "STRING"; + Type["NUMBER"] = "NUMBER"; + Type["INTEGER"] = "INTEGER"; + Type["BOOLEAN"] = "BOOLEAN"; + Type["ARRAY"] = "ARRAY"; + Type["OBJECT"] = "OBJECT"; +})(Type || (Type = {})); +var HarmCategory; +(function (HarmCategory) { + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; +})(HarmCategory || (HarmCategory = {})); +var HarmBlockMethod; +(function (HarmBlockMethod) { + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +var Mode; +(function (Mode) { + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(Mode || (Mode = {})); +var FinishReason; +(function (FinishReason) { + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + FinishReason["STOP"] = "STOP"; + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + FinishReason["SAFETY"] = "SAFETY"; + FinishReason["RECITATION"] = "RECITATION"; + FinishReason["OTHER"] = "OTHER"; + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + FinishReason["SPII"] = "SPII"; + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(FinishReason || (FinishReason = {})); +var HarmProbability; +(function (HarmProbability) { + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + HarmProbability["LOW"] = "LOW"; + HarmProbability["MEDIUM"] = "MEDIUM"; + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +var HarmSeverity; +(function (HarmSeverity) { + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +var BlockedReason; +(function (BlockedReason) { + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + BlockedReason["SAFETY"] = "SAFETY"; + BlockedReason["OTHER"] = "OTHER"; + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; +})(BlockedReason || (BlockedReason = {})); +var Modality; +(function (Modality) { + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + Modality["TEXT"] = "TEXT"; + Modality["IMAGE"] = "IMAGE"; + Modality["AUDIO"] = "AUDIO"; +})(Modality || (Modality = {})); +var State; +(function (State) { + State["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + State["ACTIVE"] = "ACTIVE"; + State["ERROR"] = "ERROR"; +})(State || (State = {})); +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + FunctionCallingConfigMode["AUTO"] = "AUTO"; + FunctionCallingConfigMode["ANY"] = "ANY"; + FunctionCallingConfigMode["NONE"] = "NONE"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +var MediaResolution; +(function (MediaResolution) { + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +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 = {})); +var PersonGeneration; +(function (PersonGeneration) { + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + ImagePromptLanguage["auto"] = "auto"; + ImagePromptLanguage["en"] = "en"; + ImagePromptLanguage["ja"] = "ja"; + ImagePromptLanguage["ko"] = "ko"; + ImagePromptLanguage["hi"] = "hi"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(FileSource || (FileSource = {})); +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 = {})); +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 = {})); +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 = {})); +var MediaModality; +(function (MediaModality) { + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + MediaModality["TEXT"] = "TEXT"; + MediaModality["IMAGE"] = "IMAGE"; + MediaModality["VIDEO"] = "VIDEO"; + MediaModality["AUDIO"] = "AUDIO"; + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * 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) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * 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), + }; +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +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' && + (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 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 counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** 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(); + } +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** 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 = []; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for (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 [Vertex AI 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-1.5-flash', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + 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: 'gemini-1.5-flash'}); + * ``` + */ + async get(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + 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: 'gemini-1.5-flash'}); + * ``` + */ + async delete(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + 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: 'gemini-1.5-flash', + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(this.apiClient, 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 __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; + } + if (part.text !== undefined && part.text === '') { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @remarks + * Expects the history to start with a user turn and then alternate between + * user and model turns. + * + * @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; + } + if (history[0].role !== 'user') { + throw new Error('History must start with a user turn.'); + } + 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; + let userInput = comprehensiveHistory[0]; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + userInput = 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(userInput); + curatedHistory.push(...modelOutput); + } + } + } + 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, 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(this.apiClient, 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; + 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; + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput); + return; + })(); + await this.sendPromise; + 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(this.apiClient, 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, + }); + this.sendPromise = streamResponse.then(() => 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) { + return curated ? extractCuratedHistory(this.history) : this.history; + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.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 && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role === 'model')) { + 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: [], + }); + } + this.history.push(userInput); + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '0.7.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 responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * Client errors raised by the GenAI API. + */ +class ClientError extends Error { + constructor(message, stackTrace) { + if (stackTrace) { + super(message, { cause: stackTrace }); + } + else { + super(message, { cause: new Error().stack }); + } + this.message = message; + this.name = 'ClientError'; + } +} +/** + * Server errors raised by the GenAI API. + */ +class ServerError extends Error { + constructor(message, stackTrace) { + if (stackTrace) { + super(message, { cause: stackTrace }); + } + else { + super(message, { cause: new Error().stack }); + } + this.message = message; + this.name = 'ServerError'; + } +} +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + // Assume that proj/api key validation occurs before they are passed in. + if (this.getProject() || this.getLocation()) { + initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + this.clientOptions.apiKey = undefined; // unset API key. + } + else { + initHttpOptions.baseUrl = `https://aiplatform.googleapis.com/`; + this.clientOptions.project = undefined; // unset project. + this.clientOptions.location = undefined; // unset location. + } + } + else { + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : 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; + } + 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 = '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) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (this.clientOptions.vertexai && + !this.clientOptions.apiKey && + !path.startsWith('projects/')) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const url = this.constructUrl(request.path, patchedHttpOptions); + 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); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + 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 url = this.constructUrl(request.path, patchedHttpOptions); + 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); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions) { + if (httpOptions && httpOptions.timeout && httpOptions.timeout > 0) { + const abortController = new AbortController(); + const signal = abortController.signal; + setTimeout(() => abortController.abort(), httpOptions.timeout); + requestInit.signal = signal; + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + 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 = ''; + 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); + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const chunkData = JSON.parse(processedChunkString); + yield yield __await(chunkData); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + 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) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * 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 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 uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + 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 ServerError('response is undefined'); + } + if (!response.ok) { + const status = response.status; + const statusText = response.statusText; + 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: 'exception parsing response', + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = `got status: ${status} ${statusText}. ${JSON.stringify(errorBody)}`; + if (status >= 400 && status < 500) { + const clientError = new ClientError(errorMessage); + throw clientError; + } + else if (status >= 500 && status < 600) { + const serverError = new ServerError(errorMessage); + throw serverError; + } + throw new Error(errorMessage); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function crossError() { + // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports + return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either: + +*Enabling conditional exports for your project [recommended]* + +*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'. +`); +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +class CrossUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + async stat(file) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return getBlobStat(file); + } + } +} +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b; + 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'; + } + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-status']) !== '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.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b['x-goog-upload-status']) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO((b/401271082): re-enable lint once CrossWebSocketFactory is implemented. +/* eslint-disable @typescript-eslint/no-unused-vars */ +class CrossWebSocketFactory { + create(url, headers, callbacks) { + throw crossError(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function listFilesConfigToMldev(apiClient, 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(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(apiClient, fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(apiClient, 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 fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(apiClient, fromError)); + } + return toObject; +} +function createFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(apiClient, fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(apiClient, 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 fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(apiClient, fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + if (Array.isArray(fromFiles)) { + setValueByPath(toObject, ['files'], fromFiles.map((item) => { + return fileFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['files'], fromFiles); + } + } + return toObject; +} +function createFileResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromHttpHeaders = getValueByPath(fromObject, ['httpHeaders']); + if (fromHttpHeaders != null) { + setValueByPath(toObject, ['httpHeaders'], fromHttpHeaders); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + 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 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. + * Somex eamples 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 + * `common.UploadFileParameters` interface. + * @return A promise that resolves to a `types.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, + * 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('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(this.apiClient, response); + return file; + }); + } + async listInternal(params) { + var _a; + 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(this.apiClient, params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a; + 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(this.apiClient, params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(this.apiClient, 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; + 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(this.apiClient, params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(this.apiClient, apiResponse); + 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; + 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(this.apiClient, params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function partToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['videoMetadata']) !== undefined) { + throw new Error('videoMetadata parameter is not supported in Gemini API.'); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToMldev(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['example']) !== undefined) { + throw new Error('example parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['pattern']) !== undefined) { + throw new Error('pattern parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['default']) !== undefined) { + throw new Error('default parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['maxLength']) !== undefined) { + throw new Error('maxLength parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['minLength']) !== undefined) { + throw new Error('minLength parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['minProperties']) !== undefined) { + throw new Error('minProperties parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['maxProperties']) !== undefined) { + throw new Error('maxProperties parameter is not supported in Gemini API.'); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['response']) !== undefined) { + throw new Error('response parameter is not supported in Gemini API.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToMldev() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(apiClient, fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(apiClient, fromVoiceConfig)); + } + return toObject; +} +function thinkingConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev(apiClient, tContent(apiClient, 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'], schemaToMldev(apiClient, tSchema(apiClient, fromResponseSchema))); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + if (Array.isArray(fromSafetySettings)) { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings.map((item) => { + return safetySettingToMldev(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings); + } + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], tTools(apiClient, tTools(apiClient, fromTools).map((item) => { + return toolToMldev(apiClient, tTool(apiClient, item)); + }))); + } + else { + setValueByPath(parentObject, ['tools'], tTools(apiClient, fromTools)); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(apiClient, fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + 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'], speechConfigToMldev(apiClient, tSpeechConfig(apiClient, fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(apiClient, fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(apiClient, 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 not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + 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); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + 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); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function countTokensConfigToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(apiClient, fromConfig)); + } + return toObject; +} +function imageToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(apiClient, fromObject, parentObject) { + 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 not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + 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 not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + if (getValueByPath(fromObject, ['resolution']) !== undefined) { + throw new Error('resolution parameter is not supported in Gemini API.'); + } + 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 not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + 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(apiClient, fromImage)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToVertex(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(apiClient, fromObject) { + const toObject = {}; + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(apiClient, fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], schemaToVertex(apiClient, fromResponse)); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToVertex() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(apiClient, fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(apiClient, fromVoiceConfig)); + } + return toObject; +} +function thinkingConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(apiClient, tContent(apiClient, 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'], schemaToVertex(apiClient, tSchema(apiClient, fromResponseSchema))); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + if (Array.isArray(fromSafetySettings)) { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings.map((item) => { + return safetySettingToVertex(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings); + } + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], tTools(apiClient, tTools(apiClient, fromTools).map((item) => { + return toolToVertex(apiClient, tTool(apiClient, item)); + }))); + } + else { + setValueByPath(parentObject, ['tools'], tTools(apiClient, fromTools)); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(apiClient, 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(apiClient, tSpeechConfig(apiClient, fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(apiClient, fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(apiClient, fromObject, parentObject) { + 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 fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function countTokensConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToVertex(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function imageToVertex(apiClient, fromObject) { + 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(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToVertex(apiClient, fromObject, parentObject) { + 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); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + 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(apiClient, fromImage)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function candidateFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(apiClient, fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(apiClient, 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 fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + 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) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + if (Array.isArray(fromCandidates)) { + setValueByPath(toObject, ['candidates'], fromCandidates.map((item) => { + return candidateFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['candidates'], fromCandidates); + } + } + 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 fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + if (Array.isArray(fromEmbeddings)) { + setValueByPath(toObject, ['embeddings'], fromEmbeddings.map((item) => { + return contentEmbeddingFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['embeddings'], fromEmbeddings); + } + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(apiClient, fromObject) { + 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 generatedImageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(apiClient, fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(apiClient, fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + if (Array.isArray(fromGeneratedImages)) { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages.map((item) => { + return generatedImageFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages); + } + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(apiClient, fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function countTokensResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + 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 videoFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev$1(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromMldev$1(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromMldev$1(apiClient, fromResult)); + } + return toObject; +} +function partFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function candidateFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(apiClient, fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(apiClient, fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + 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) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + if (Array.isArray(fromCandidates)) { + setValueByPath(toObject, ['candidates'], fromCandidates.map((item) => { + return candidateFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['candidates'], fromCandidates); + } + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + 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 fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(apiClient, fromObject) { + 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); + } + return toObject; +} +function contentEmbeddingFromVertex(apiClient, fromObject) { + 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(apiClient, fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + if (Array.isArray(fromEmbeddings)) { + setValueByPath(toObject, ['embeddings'], fromEmbeddings.map((item) => { + return contentEmbeddingFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['embeddings'], fromEmbeddings); + } + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(apiClient, fromMetadata)); + } + return toObject; +} +function imageFromVertex(apiClient, fromObject) { + 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(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(apiClient, fromObject) { + 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 generatedImageFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(apiClient, 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(apiClient, fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + if (Array.isArray(fromGeneratedImages)) { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages.map((item) => { + return generatedImageFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages); + } + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(apiClient, fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function countTokensResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex$1(apiClient, 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(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex$1(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromVertex$1(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, ['response']); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromVertex$1(apiClient, fromResult)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Converters for live client. + */ +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig !== undefined && fromConfig !== null) { + setValueByPath(toObject, ['setup'], liveConnectConfigToMldev(apiClient, fromConfig)); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel !== undefined) { + setValueByPath(toObject, ['setup', 'model'], fromModel); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig !== undefined && fromConfig !== null) { + setValueByPath(toObject, ['setup'], liveConnectConfigToVertex(apiClient, fromConfig)); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel !== undefined) { + setValueByPath(toObject, ['setup', 'model'], fromModel); + } + return toObject; +} +function liveServerMessageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete !== undefined) { + setValueByPath(toObject, ['setupComplete'], fromSetupComplete); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent !== undefined && fromServerContent !== null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(apiClient, fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall !== undefined && fromToolCall !== null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(apiClient, fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation !== undefined && + fromToolCallCancellation !== null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(apiClient, fromToolCallCancellation)); + } + return toObject; +} +function liveServerMessageFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete !== undefined) { + setValueByPath(toObject, ['setupComplete'], fromSetupComplete); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent !== undefined && fromServerContent !== null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(apiClient, fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall !== undefined && fromToolCall !== null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(apiClient, fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation !== undefined && + fromToolCallCancellation !== null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(apiClient, fromToolCallCancellation)); + } + return toObject; +} +function liveConnectConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (fromGenerationConfig !== undefined) { + setValueByPath(toObject, ['generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities !== undefined) { + setValueByPath(toObject, ['generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig !== undefined) { + setValueByPath(toObject, ['generationConfig', 'speechConfig'], fromSpeechConfig); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) { + setValueByPath(toObject, ['systemInstruction'], contentToMldev(apiClient, fromSystemInstruction)); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (fromTools !== undefined && + fromTools !== null && + Array.isArray(fromTools)) { + setValueByPath(toObject, ['tools'], fromTools.map((item) => { + return toolToMldev(apiClient, item); + })); + } + return toObject; +} +function liveConnectConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (fromGenerationConfig !== undefined) { + setValueByPath(toObject, ['generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities !== undefined) { + setValueByPath(toObject, ['generationConfig', 'responseModalities'], fromResponseModalities); + } + else { + // Set default to AUDIO to align with MLDev API. + setValueByPath(toObject, ['generationConfig', 'responseModalities'], ['AUDIO']); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig !== undefined) { + setValueByPath(toObject, ['generationConfig', 'speechConfig'], fromSpeechConfig); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) { + setValueByPath(toObject, ['systemInstruction'], contentToVertex(apiClient, fromSystemInstruction)); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (fromTools !== undefined && + fromTools !== null && + Array.isArray(fromTools)) { + setValueByPath(toObject, ['tools'], fromTools.map((item) => { + return toolToVertex(apiClient, item); + })); + } + return toObject; +} +function liveServerContentFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn !== undefined && fromModelTurn !== null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev(apiClient, fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete !== undefined) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted !== undefined) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + return toObject; +} +function liveServerContentFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn !== undefined && fromModelTurn !== null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex(apiClient, fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete !== undefined) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted !== undefined) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + return toObject; +} +function functionCallFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId !== undefined) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs !== undefined) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName !== undefined) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function functionCallFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs !== undefined) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName !== undefined) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls !== undefined && + fromFunctionCalls !== null && + Array.isArray(fromFunctionCalls)) { + setValueByPath(toObject, ['functionCalls'], fromFunctionCalls.map((item) => { + return functionCallFromMldev(apiClient, item); + })); + } + return toObject; +} +function liveServerToolCallFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls !== undefined && + fromFunctionCalls !== null && + Array.isArray(fromFunctionCalls)) { + setValueByPath(toObject, ['functionCalls'], fromFunctionCalls.map((item) => { + return functionCallFromVertex(apiClient, item); + })); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds !== undefined) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds !== undefined) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} + +/** + * @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) { + let serverMessage; + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + if (apiClient.isVertexAI()) { + serverMessage = liveServerMessageFromVertex(apiClient, data); + } + else { + serverMessage = liveServerMessageFromMldev(apiClient, data); + } + 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; + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental + + @remarks + If using the Gemini API, Live is currently only supported behind API + version `v1alpha`. Ensure that the API version is set to `v1alpha` when + initializing the SDK if relying on the Gemini API. + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + 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; + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const headers = mapToHeaders(this.apiClient.getDefaultHeaders()); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateContent?key=${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; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(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(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(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + 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); + } + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } +} +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(apiClient, params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(apiClient, item)); + } + else { + contents = contents.map((item) => contentToMldev(apiClient, 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 }, + }; + } + tLiveClientRealtimeInput(apiClient, params) { + let clientMessage = {}; + if (!('media' in params) || !params.media) { + throw new Error(`Failed to convert realtime input "media", type: '${typeof params.media}'`); + } + // LiveClientRealtimeInput + clientMessage = { realtimeInput: { mediaChunks: [params.media] } }; + return clientMessage; + } + 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) { + if (params.media == null) { + throw new Error('Media is required.'); + } + const clientMessage = this.tLiveClientRealtimeInput(this.apiClient, 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 + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + 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 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI 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) => { + return await this.generateContentInternal(params); + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI 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) => { + return await this.generateContentStreamInternal(params); + }; + /** + * Generates an image based on a text description and configuration. + * + * @param model - The model to use. + * @param prompt - A text description of the image to generate. + * @param [config] - The config for image generation. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + 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, + }; + } + else { + response = { + generatedImages: generatedImages, + }; + } + return response; + }); + }; + } + async generateContentInternal(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(this.apiClient, 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b; + 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['config']; + 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, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_1, _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(apiClient, chunk); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _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(apiClient, chunk); + 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_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_2) throw e_2.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 embedContent(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * 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 ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new GenerateImagesResponse(); + 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; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(this.apiClient, 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(this.apiClient, 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; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * 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', + * 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.get({operation: operation}); + * } + * + * console.log(operation.result?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideos(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex$1(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev$1(this.apiClient, apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function getOperationParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(apiClient, 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); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromMldev(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromMldev(apiClient, fromResult)); + } + return toObject; +} +function videoFromVertex(apiClient, 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(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromVertex(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, ['response']); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromVertex(apiClient, fromResult)); + } + return toObject; +} + +/** + * @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 operation The Operation object returned by a previous API call. + * @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]; + var httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + return this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + } + else { + return this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(this.apiClient, params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = getOperationParametersToMldev(this.apiClient, params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(this.apiClient, apiResponse); + return resp; + }); + } + } + async fetchPredictVideosOperationInternal(params) { + var _a; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(this.apiClient, params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * 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 {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @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 { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error(`An API Key must be set when running in an unspecified environment.\n + ${crossError().message}`); + } + this.vertexai = (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross', + uploader: new CrossUploader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory()); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + } +} + +export { BlockedReason, Caches, Chat, Chats, ComputeTokensResponse, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DynamicRetrievalConfigMode, EmbedContentResponse, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpResponse, ImagePromptLanguage, Language, ListCachedContentsResponse, ListFilesResponse, Live, LiveClientToolResponse, LiveSendToolResponseParameters, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, Operations, Outcome, PagedItem, Pager, PersonGeneration, ReplayResponse, SafetyFilterLevel, Session, State, SubjectReferenceType, Type, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent }; +//# sourceMappingURL=index.mjs.map diff --git a/node_modules/@google/genai/dist/index.mjs.map b/node_modules/@google/genai/dist/index.mjs.map new file mode 100644 index 0000000..0169007 --- /dev/null +++ b/node_modules/@google/genai/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../src/_common.ts","../src/_transformers.ts","../src/converters/_caches_converters.ts","../src/pagers.ts","../src/types.ts","../src/caches.ts","../src/chats.ts","../src/_api_client.ts","../src/cross/_cross_error.ts","../src/cross/_cross_uploader.ts","../src/cross/_cross_websocket.ts","../src/converters/_files_converters.ts","../src/files.ts","../src/converters/_models_converters.ts","../src/converters/_live_converters.ts","../src/live.ts","../src/models.ts","../src/converters/_operations_converters.ts","../src/operations.ts","../src/web/_web_auth.ts","../src/client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {UploadFileConfig} from './types';\n\nexport class BaseModule {}\n\n// TODO (b/406332263): Move this to a place where it can be linked for doc.\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client';\nimport * as types from './types';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tPart(\n apiClient: ApiClient,\n origin?: types.PartUnion | null,\n): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(\n apiClient: ApiClient,\n origin?: types.PartListUnion | null,\n): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(apiClient, item as types.PartUnion)!);\n }\n return [tPart(apiClient, origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isUserPart(origin: unknown): boolean {\n if (origin === null || origin === undefined) {\n return false;\n }\n if (_isFunctionCallPart(origin)) {\n return false;\n }\n return true;\n}\n\nfunction _areUserParts(origin: types.PartListUnion[]): boolean {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n return false;\n }\n return origin.every(_isUserPart);\n}\n\nexport function tContent(\n apiClient: ApiClient,\n origin?: types.ContentUnion,\n): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // @ts-expect-error: _isContent is a utility function that checks if the\n // origin is a Content.\n return origin;\n }\n\n if (_isUserPart(origin)) {\n return {\n role: 'user',\n parts: tParts(apiClient, origin as types.PartListUnion)!,\n };\n } else {\n return {\n role: 'model',\n parts: tParts(apiClient, origin as types.PartListUnion)!,\n };\n }\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(apiClient, item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(apiClient, origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map(\n (item) => tContent(apiClient, item as types.ContentUnion)!,\n );\n }\n return [tContent(apiClient, origin as types.ContentUnion)!];\n}\n\nfunction _appendAccumulatedPartsAsContent(\n apiClient: ApiClient,\n result: types.Content[],\n accumulatedParts: types.PartUnion[],\n) {\n if (accumulatedParts.length === 0) {\n return;\n }\n if (_areUserParts(accumulatedParts)) {\n result.push({\n role: 'user',\n parts: tParts(apiClient, accumulatedParts),\n });\n } else {\n result.push({\n role: 'model',\n parts: tParts(apiClient, accumulatedParts),\n });\n }\n accumulatedParts.length = 0; // clear the array inplace\n}\n\nfunction _handleCurrentPart(\n apiClient: ApiClient,\n result: types.Content[],\n accumulatedParts: types.PartUnion[],\n currentPart: types.PartUnion,\n) {\n if (_isUserPart(currentPart) === _areUserParts(accumulatedParts)) {\n accumulatedParts.push(currentPart);\n } else {\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n accumulatedParts.length = 0;\n accumulatedParts.push(currentPart);\n }\n}\n\nexport function tContents(\n apiClient: ApiClient,\n origin?: types.ContentListUnion,\n): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n return [tContent(apiClient, origin)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n\n for (const content of origin) {\n if (_isContent(content)) {\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n // @ts-expect-error: content is a Content here\n result.push(content);\n } else if (\n typeof content === 'string' ||\n (typeof content === 'object' && !Array.isArray(content))\n ) {\n // @ts-expect-error: content is a part here\n _handleCurrentPart(apiClient, result, accumulatedParts, content);\n } else if (Array.isArray(content)) {\n // if there're consecutive user parts before the list,\n // convert to UserContent and append to result\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n result.push({\n role: 'user',\n parts: tParts(apiClient, content),\n });\n } else {\n throw new Error(`Unsupported content type: ${typeof content}`);\n }\n }\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n\n return result;\n}\n\nexport function processSchema(apiClient: ApiClient, schema: types.Schema) {\n if (!apiClient.isVertexAI()) {\n if ('default' in schema) {\n throw new Error(\n 'Default value is not supported in the response schema for the Gemini API.',\n );\n }\n }\n\n if ('anyOf' in schema) {\n if (schema['anyOf'] !== undefined) {\n for (const subSchema of schema['anyOf']) {\n processSchema(apiClient, subSchema);\n }\n }\n }\n\n if ('items' in schema) {\n if (schema['items'] !== undefined) {\n processSchema(apiClient, schema['items']);\n }\n }\n\n if ('properties' in schema) {\n if (schema['properties'] !== undefined) {\n for (const subSchema of Object.values(schema['properties'])) {\n processSchema(apiClient, subSchema);\n }\n }\n }\n}\n\nexport function tSchema(\n apiClient: ApiClient,\n schema: types.Schema,\n): types.Schema {\n processSchema(apiClient, schema);\n return schema;\n}\n\nexport function tSpeechConfig(\n apiClient: ApiClient,\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object' && 'voiceConfig' in speechConfig) {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tTool(apiClient: ApiClient, tool: types.Tool): types.Tool {\n return tool;\n}\n\nexport function tTools(\n apiClient: ApiClient,\n tool: types.Tool[] | unknown,\n): types.Tool[] {\n if (!Array.isArray(tool)) {\n throw new Error('tool is required and must be an array of Tools');\n }\n return tool;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(\n apiClient: ApiClient,\n status: string | unknown,\n): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(\n apiClient: ApiClient,\n fromImageBytes: string | unknown,\n): string {\n if (typeof fromImageBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromImageBytes;\n}\nexport function tFileName(\n apiClient: ApiClient,\n fromName: string | unknown,\n): string {\n if (typeof fromName !== 'string') {\n throw new Error('fromName must be a string');\n }\n // Remove the files/ prefx for MLdev urls to get the actual name of the file.\n if (fromName.startsWith('files/')) {\n return fromName.split('files/')[1];\n }\n return fromName;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function partToMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['videoMetadata']) !== undefined) {\n throw new Error('videoMetadata parameter is not supported in Gemini API.');\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['example']) !== undefined) {\n throw new Error('example parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['pattern']) !== undefined) {\n throw new Error('pattern parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['default']) !== undefined) {\n throw new Error('default parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxLength']) !== undefined) {\n throw new Error('maxLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minLength']) !== undefined) {\n throw new Error('minLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minProperties']) !== undefined) {\n throw new Error('minProperties parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxProperties']) !== undefined) {\n throw new Error('maxProperties parameter is not supported in Gemini API.');\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['response']) !== undefined) {\n throw new Error('response parameter is not supported in Gemini API.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToMldev(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToMldev());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(apiClient, fromToolConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partToVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n schemaToVertex(apiClient, fromResponse),\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToVertex(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToVertex());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(apiClient, fromToolConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n apiClient: ApiClient,\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n if (Array.isArray(fromCachedContents)) {\n common.setValueByPath(\n toObject,\n ['cachedContents'],\n fromCachedContents.map((item) => {\n return cachedContentFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['cachedContents'], fromCachedContents);\n }\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n apiClient: ApiClient,\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n if (Array.isArray(fromCachedContents)) {\n common.setValueByPath(\n toObject,\n ['cachedContents'],\n fromCachedContents.map((item) => {\n return cachedContentFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['cachedContents'], fromCachedContents);\n }\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nexport enum Outcome {\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n OUTCOME_OK = 'OUTCOME_OK',\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\nexport enum Language {\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n PYTHON = 'PYTHON',\n}\n\nexport enum Type {\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n STRING = 'STRING',\n NUMBER = 'NUMBER',\n INTEGER = 'INTEGER',\n BOOLEAN = 'BOOLEAN',\n ARRAY = 'ARRAY',\n OBJECT = 'OBJECT',\n}\n\nexport enum HarmCategory {\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n}\n\nexport enum HarmBlockMethod {\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n SEVERITY = 'SEVERITY',\n PROBABILITY = 'PROBABILITY',\n}\n\nexport enum HarmBlockThreshold {\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n OFF = 'OFF',\n}\n\nexport enum Mode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\nexport enum FinishReason {\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n STOP = 'STOP',\n MAX_TOKENS = 'MAX_TOKENS',\n SAFETY = 'SAFETY',\n RECITATION = 'RECITATION',\n OTHER = 'OTHER',\n BLOCKLIST = 'BLOCKLIST',\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n SPII = 'SPII',\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\nexport enum HarmProbability {\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n NEGLIGIBLE = 'NEGLIGIBLE',\n LOW = 'LOW',\n MEDIUM = 'MEDIUM',\n HIGH = 'HIGH',\n}\n\nexport enum HarmSeverity {\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\nexport enum BlockedReason {\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n SAFETY = 'SAFETY',\n OTHER = 'OTHER',\n BLOCKLIST = 'BLOCKLIST',\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n}\n\nexport enum Modality {\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n TEXT = 'TEXT',\n IMAGE = 'IMAGE',\n AUDIO = 'AUDIO',\n}\n\nexport enum State {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n ACTIVE = 'ACTIVE',\n ERROR = 'ERROR',\n}\n\nexport enum DynamicRetrievalConfigMode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\nexport enum FunctionCallingConfigMode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n AUTO = 'AUTO',\n ANY = 'ANY',\n NONE = 'NONE',\n}\n\nexport enum MediaResolution {\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\nexport enum PersonGeneration {\n DONT_ALLOW = 'DONT_ALLOW',\n ALLOW_ADULT = 'ALLOW_ADULT',\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\nexport enum ImagePromptLanguage {\n auto = 'auto',\n en = 'en',\n ja = 'ja',\n ko = 'ko',\n hi = 'hi',\n}\n\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\nexport enum MediaModality {\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n TEXT = 'TEXT',\n IMAGE = 'IMAGE',\n VIDEO = 'VIDEO',\n AUDIO = 'AUDIO',\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Metadata describes the input video content. */\nexport declare interface VideoMetadata {\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [FunctionDeclaration] tool and [FunctionCallingConfig] mode is set to [Mode.CODE]. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. Required. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** The id of the function call this response is for. Populated by the client\n to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Required. Raw bytes. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n left blank or unset. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n}\n\n/** Schema that defines the format of input and output data.\n\n Represents a select subset of an OpenAPI 3.0 schema object.\n */\nexport declare interface Schema {\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Describes the output from the function in the OpenAPI JSON Schema\n Object format. */\n response?: Schema;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. This field is only used by the Gemini Developer API services. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use.\n */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. e.g. 'gemini-1.5-pro-001'. */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response media type of the generated candidate text.\n */\n responseMimeType?: string;\n /** Schema that the generated candidate text must adhere to.\n */\n responseSchema?: SchemaUnion;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. This list must have the same size as the grounding_chunk_indices. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** Identifier for each response.\n */\n responseId?: string;\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `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.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport /** Optional parameters for the embed_content method. */\ndeclare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images.\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** Whether to use the prompt rewriting logic.\n */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both.\n */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories.\n */\n categories?: string[];\n /** List of scores of each categories.\n */\n scores?: number[];\n /** Internal use only.\n */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data.\n */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response.\n */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content.\n */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled.\n */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** List of generated images.\n */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True.\n */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional. Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 1280x720, 1920x1080 are supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation progress. */\n pubsubTopic?: string;\n /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** Class that represents the parameters for generating an image. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos. Optional for image to video use cases. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt is provided. */\n image?: Image;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes. */\n videoBytes?: string;\n /** Video encoding, for example \"video/mp4\". */\n mimeType?: string;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** A video generation operation. */\nexport declare interface GenerateVideosOperation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The normal response of the operation in case of success. */\n response?: Record;\n /** The generated videos. */\n result?: GenerateVideosResponse;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-1.5-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n onopen?: (() => void) | null;\n onmessage: (e: LiveServerMessage) => void;\n onerror?: ((e: ErrorEvent) => void) | null;\n onclose?: ((e: CloseEvent) => void) | null;\n}\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression if the ``output_mime_type`` is\n ``image/jpeg``. */\n outputCompressionQuality?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport declare interface RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport declare interface MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport declare interface ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport declare interface StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport declare interface SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n}\n\n/** Sent in response to a `LiveGenerateContentSetup` message from the client. */\nexport declare interface LiveServerSetupComplete {}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Response message for API call. */\nexport declare interface LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n\nThe following fields are supported:\n- `response_logprobs`\n- `response_mime_type`\n- `logprobs`\n- `response_schema`\n- `stop_sequence`\n- `routing_config`\n- `audio_timestamp`\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: Content;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** User input that is sent in real time.\n\n This is different from `ClientContentUpdate` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `ClientContentUpdate` and the `RealtimeUpdate`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: Content;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-1.5-pro', etc. See gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media: Blob;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters {\n /** The operation to be retrieved. */\n operation: GenerateVideosOperation;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = ContentUnion[] | ContentUnion;\n\nexport type SchemaUnion = Schema;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolListUnion = Tool[];\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_caches_converters';\nimport {PagedItem, Pager} from './pagers';\nimport * as types from './types';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference] (https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference] (https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-1.5-flash',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: 'gemini-1.5-flash'});\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: 'gemini-1.5-flash'});\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromVertex();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromMldev();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: 'gemini-1.5-flash',\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listCachedContentsResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listCachedContentsResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client';\nimport * as t from './_transformers';\nimport {Models} from './models';\nimport * as types from './types';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\n if (content.parts === undefined || content.parts.length === 0) {\n return false;\n }\n for (const part of content.parts) {\n if (part === undefined || Object.keys(part).length === 0) {\n return false;\n }\n if (part.text !== undefined && part.text === '') {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @remarks\n * Expects the history to start with a user turn and then alternate between\n * user and model turns.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n if (history[0].role !== 'user') {\n throw new Error('History must start with a user turn.');\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n let userInput = comprehensiveHistory[0];\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n userInput = comprehensiveHistory[i];\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(userInput);\n curatedHistory.push(...modelOutput);\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n params.history,\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(this.apiClient, params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(inputContent, modelOutput);\n return;\n })();\n await this.sendPromise;\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(this.apiClient, params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = streamResponse.then(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n return curated ? extractCuratedHistory(this.history) : this.history;\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role === 'model')\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n this.history.push(userInput);\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth';\nimport * as common from './_common';\nimport {Uploader} from './_uploader';\nimport {File, HttpOptions, HttpResponse, UploadFileConfig} from './types';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst USER_AGENT_HEADER = 'User-Agent';\nconst GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '0.7.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Client errors raised by the GenAI API.\n */\nexport class ClientError extends Error {\n constructor(message: string, stackTrace?: string) {\n if (stackTrace) {\n super(message, {cause: stackTrace});\n } else {\n super(message, {cause: new Error().stack});\n }\n this.message = message;\n this.name = 'ClientError';\n }\n}\n\n/**\n * Server errors raised by the GenAI API.\n */\nexport class ServerError extends Error {\n constructor(message: string, stackTrace?: string) {\n if (stackTrace) {\n super(message, {cause: stackTrace});\n } else {\n super(message, {cause: new Error().stack});\n }\n this.message = message;\n this.name = 'ServerError';\n }\n}\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n // Assume that proj/api key validation occurs before they are passed in.\n if (this.getProject() || this.getLocation()) {\n initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n this.clientOptions.apiKey = undefined; // unset API key.\n } else {\n initHttpOptions.baseUrl = `https://aiplatform.googleapis.com/`;\n this.clientOptions.project = undefined; // unset project.\n this.clientOptions.location = undefined; // unset location.\n }\n } else {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(path: string, httpOptions: HttpOptions): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (\n this.clientOptions.vertexai &&\n !this.clientOptions.apiKey &&\n !path.startsWith('projects/')\n ) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const url = this.constructUrl(request.path, patchedHttpOptions);\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const url = this.constructUrl(request.path, patchedHttpOptions);\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n ): Promise {\n if (httpOptions && httpOptions.timeout && httpOptions.timeout > 0) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n setTimeout(() => abortController.abort(), httpOptions.timeout);\n requestInit.signal = signal;\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value);\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const chunkData = JSON.parse(processedChunkString);\n yield chunkData;\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new ServerError('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n const statusText: string = response.statusText;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: 'exception parsing response',\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = `got status: ${status} ${statusText}. ${JSON.stringify(\n errorBody,\n )}`;\n if (status >= 400 && status < 500) {\n const clientError = new ClientError(errorMessage);\n throw clientError;\n } else if (status >= 500 && status < 600) {\n const serverError = new ServerError(errorMessage);\n throw serverError;\n }\n throw new Error(errorMessage);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function crossError(): Error {\n // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports\n return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either:\n\n*Enabling conditional exports for your project [recommended]*\n\n*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'.\n`);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client';\nimport {FileStat, Uploader} from '../_uploader';\nimport {File, HttpResponse} from '../types';\n\nimport {crossError} from './_cross_error';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.['x-goog-upload-status'] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.['x-goog-upload-status'] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n WebSocketCallbacks,\n WebSocketFactory,\n WebSocket as Ws,\n} from '../_websocket';\nimport {crossError} from './_cross_error';\n\n// TODO((b/401271082): re-enable lint once CrossWebSocketFactory is implemented.\n/* eslint-disable @typescript-eslint/no-unused-vars */\nexport class CrossWebSocketFactory implements WebSocketFactory {\n create(\n url: string,\n headers: Record,\n callbacks: WebSocketCallbacks,\n ): Ws {\n throw crossError();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function listFilesConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n apiClient: ApiClient,\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(\n apiClient: ApiClient,\n fromObject: types.File,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(\n toObject,\n ['error'],\n fileStatusToMldev(apiClient, fromError),\n );\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(apiClient, fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'file'],\n t.tFileName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'file'],\n t.tFileName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n apiClient: ApiClient,\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(\n apiClient: ApiClient,\n fromObject: types.File,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(\n toObject,\n ['error'],\n fileStatusFromMldev(apiClient, fromError),\n );\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n if (Array.isArray(fromFiles)) {\n common.setValueByPath(\n toObject,\n ['files'],\n fromFiles.map((item) => {\n return fileFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['files'], fromFiles);\n }\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromHttpHeaders = common.getValueByPath(fromObject, ['httpHeaders']);\n if (fromHttpHeaders != null) {\n common.setValueByPath(toObject, ['httpHeaders'], fromHttpHeaders);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_files_converters';\nimport {PagedItem, Pager} from './pagers';\nimport * as types from './types';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `common.UploadFileParameters` interface.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: common.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(this.apiClient, response);\n return file as types.File;\n });\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(this.apiClient, apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteFileResponseFromMldev();\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function partToMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['videoMetadata']) !== undefined) {\n throw new Error('videoMetadata parameter is not supported in Gemini API.');\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['example']) !== undefined) {\n throw new Error('example parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['pattern']) !== undefined) {\n throw new Error('pattern parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['default']) !== undefined) {\n throw new Error('default parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxLength']) !== undefined) {\n throw new Error('maxLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minLength']) !== undefined) {\n throw new Error('minLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minProperties']) !== undefined) {\n throw new Error('minProperties parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxProperties']) !== undefined) {\n throw new Error('maxProperties parameter is not supported in Gemini API.');\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n apiClient: ApiClient,\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['response']) !== undefined) {\n throw new Error('response parameter is not supported in Gemini API.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToMldev(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToMldev());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(apiClient, fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(apiClient, fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(apiClient, t.tSchema(apiClient, fromResponseSchema)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n if (Array.isArray(fromSafetySettings)) {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings.map((item) => {\n return safetySettingToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings,\n );\n }\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(\n apiClient,\n t.tTools(apiClient, fromTools).map((item) => {\n return toolToMldev(apiClient, t.tTool(apiClient, item));\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(apiClient, fromTools),\n );\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(apiClient, fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(\n apiClient,\n t.tSpeechConfig(apiClient, fromSpeechConfig),\n ),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(apiClient, fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(apiClient, fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n if (common.getValueByPath(fromObject, ['resolution']) !== undefined) {\n throw new Error('resolution parameter is not supported in Gemini API.');\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(apiClient, fromImage),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partToVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n apiClient: ApiClient,\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n schemaToVertex(apiClient, fromResponse),\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToVertex(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToVertex());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(apiClient, fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(apiClient, fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(apiClient, t.tSchema(apiClient, fromResponseSchema)),\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n if (Array.isArray(fromSafetySettings)) {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings.map((item) => {\n return safetySettingToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings,\n );\n }\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(\n apiClient,\n t.tTools(apiClient, fromTools).map((item) => {\n return toolToVertex(apiClient, t.tTool(apiClient, item));\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(apiClient, fromTools),\n );\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(apiClient, fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(\n apiClient,\n t.tSpeechConfig(apiClient, fromSpeechConfig),\n ),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(apiClient, fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(apiClient, fromImage),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partFromMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n apiClient: ApiClient,\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n apiClient: ApiClient,\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromMldev(apiClient, fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(apiClient, fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n if (Array.isArray(fromCandidates)) {\n common.setValueByPath(\n toObject,\n ['candidates'],\n fromCandidates.map((item) => {\n return candidateFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['candidates'], fromCandidates);\n }\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n apiClient: ApiClient,\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n if (Array.isArray(fromEmbeddings)) {\n common.setValueByPath(\n toObject,\n ['embeddings'],\n fromEmbeddings.map((item) => {\n return contentEmbeddingFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['embeddings'], fromEmbeddings);\n }\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['imageBytes'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n apiClient: ApiClient,\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['image'],\n imageFromMldev(apiClient, fromImage),\n );\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(apiClient, fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n if (Array.isArray(fromGeneratedImages)) {\n common.setValueByPath(\n toObject,\n ['generatedImages'],\n fromGeneratedImages.map((item) => {\n return generatedImageFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedImages'], fromGeneratedImages);\n }\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(apiClient, fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromMldev(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromMldev(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n apiClient: ApiClient,\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n apiClient: ApiClient,\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(apiClient, fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(apiClient, fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n if (Array.isArray(fromCandidates)) {\n common.setValueByPath(\n toObject,\n ['candidates'],\n fromCandidates.map((item) => {\n return candidateFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['candidates'], fromCandidates);\n }\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n apiClient: ApiClient,\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n apiClient: ApiClient,\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(apiClient, fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n if (Array.isArray(fromEmbeddings)) {\n common.setValueByPath(\n toObject,\n ['embeddings'],\n fromEmbeddings.map((item) => {\n return contentEmbeddingFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['embeddings'], fromEmbeddings);\n }\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(apiClient, fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['imageBytes'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n apiClient: ApiClient,\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['image'],\n imageFromVertex(apiClient, fromImage),\n );\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(apiClient, fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n if (Array.isArray(fromGeneratedImages)) {\n common.setValueByPath(\n toObject,\n ['generatedImages'],\n fromGeneratedImages.map((item) => {\n return generatedImageFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedImages'], fromGeneratedImages);\n }\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(apiClient, fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromVertex(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, ['response']);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromVertex(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as types from '../types';\nimport {\n contentFromMldev,\n contentFromVertex,\n contentToMldev,\n contentToVertex,\n toolToMldev,\n toolToVertex,\n} from './_models_converters';\n\n/**\n * Converters for live client.\n */\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): types.LiveClientMessage {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig !== undefined && fromConfig !== null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveConnectConfigToMldev(apiClient, fromConfig),\n );\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel !== undefined) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): types.LiveClientMessage {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig !== undefined && fromConfig !== null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveConnectConfigToVertex(apiClient, fromConfig),\n );\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel !== undefined) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerMessage,\n): types.LiveServerMessage {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete !== undefined) {\n common.setValueByPath(toObject, ['setupComplete'], fromSetupComplete);\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent !== undefined && fromServerContent !== null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(apiClient, fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall !== undefined && fromToolCall !== null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(apiClient, fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (\n fromToolCallCancellation !== undefined &&\n fromToolCallCancellation !== null\n ) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(\n apiClient,\n fromToolCallCancellation,\n ),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerMessage,\n): types.LiveServerMessage {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete !== undefined) {\n common.setValueByPath(toObject, ['setupComplete'], fromSetupComplete);\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent !== undefined && fromServerContent !== null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(apiClient, fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall !== undefined && fromToolCall !== null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(apiClient, fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (\n fromToolCallCancellation !== undefined &&\n fromToolCallCancellation !== null\n ) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(\n apiClient,\n fromToolCallCancellation,\n ),\n );\n }\n\n return toObject;\n}\n\nfunction liveConnectConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConfig,\n): types.LiveClientSetup {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig !== undefined) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'speechConfig'],\n fromSpeechConfig,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(apiClient, fromSystemInstruction),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (\n fromTools !== undefined &&\n fromTools !== null &&\n Array.isArray(fromTools)\n ) {\n common.setValueByPath(\n toObject,\n ['tools'],\n fromTools.map((item: types.Tool) => {\n return toolToMldev(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveConnectConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConfig,\n): types.LiveClientSetup {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig !== undefined) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n } else {\n // Set default to AUDIO to align with MLDev API.\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n ['AUDIO'],\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'speechConfig'],\n fromSpeechConfig,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(apiClient, fromSystemInstruction),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (\n fromTools !== undefined &&\n fromTools !== null &&\n Array.isArray(fromTools)\n ) {\n common.setValueByPath(\n toObject,\n ['tools'],\n fromTools.map((item: types.Tool) => {\n return toolToVertex(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerContentFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerContent,\n): types.LiveServerContent {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn !== undefined && fromModelTurn !== null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(apiClient, fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete !== undefined) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted !== undefined) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n return toObject;\n}\n\nfunction liveServerContentFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerContent,\n): types.LiveServerContent {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn !== undefined && fromModelTurn !== null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(apiClient, fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete !== undefined) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted !== undefined) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n return toObject;\n}\n\nfunction functionCallFromMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCall,\n): types.FunctionCall {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId !== undefined) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs !== undefined) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName !== undefined) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nfunction functionCallFromVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCall,\n): types.FunctionCall {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs !== undefined) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName !== undefined) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCall,\n): types.LiveServerToolCall {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (\n fromFunctionCalls !== undefined &&\n fromFunctionCalls !== null &&\n Array.isArray(fromFunctionCalls)\n ) {\n common.setValueByPath(\n toObject,\n ['functionCalls'],\n fromFunctionCalls.map((item: types.FunctionCall) => {\n return functionCallFromMldev(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCall,\n): types.LiveServerToolCall {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (\n fromFunctionCalls !== undefined &&\n fromFunctionCalls !== null &&\n Array.isArray(fromFunctionCalls)\n ) {\n common.setValueByPath(\n toObject,\n ['functionCalls'],\n fromFunctionCalls.map((item: types.FunctionCall) => {\n return functionCallFromVertex(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallCancellationFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCallCancellation,\n): types.LiveServerToolCallCancellation {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds !== undefined) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallCancellationFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCallCancellation,\n): types.LiveServerToolCallCancellation {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds !== undefined) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client';\nimport {Auth} from './_auth';\nimport * as t from './_transformers';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket';\nimport * as converters from './converters/_live_converters';\nimport {contentToMldev, contentToVertex} from './converters/_models_converters';\nimport * as types from './types';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n let serverMessage: types.LiveServerMessage;\n let data: types.LiveServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveServerMessage;\n }\n if (apiClient.isVertexAI()) {\n serverMessage = converters.liveServerMessageFromVertex(apiClient, data);\n } else {\n serverMessage = converters.liveServerMessageFromMldev(apiClient, data);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental\n\n @remarks\n If using the Gemini API, Live is currently only supported behind API\n version `v1alpha`. Ensure that the API version is set to `v1alpha` when\n initializing the SDK if relying on the Gemini API.\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n const session = await ai.live.connect({\n model: 'gemini-2.0-flash-exp',\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateContent?key=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: types.LiveClientMessage = {};\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(\n apiClient,\n params.turns as types.ContentListUnion,\n );\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(apiClient, item));\n } else {\n contents = contents.map((item) => contentToMldev(apiClient, item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClientRealtimeInput(\n apiClient: ApiClient,\n params: types.LiveSendRealtimeInputParameters,\n ): types.LiveClientMessage {\n let clientMessage: types.LiveClientMessage = {};\n if (!('media' in params) || !params.media) {\n throw new Error(\n `Failed to convert realtime input \"media\", type: '${typeof params.media}'`,\n );\n }\n\n // LiveClientRealtimeInput\n clientMessage = {realtimeInput: {mediaChunks: [params.media]}};\n return clientMessage;\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n if (params.media == null) {\n throw new Error('Media is required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClientRealtimeInput(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n const session = await ai.live.connect({\n model: 'gemini-2.0-flash-exp',\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_models_converters';\nimport * as types from './types';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n return await this.generateContentInternal(params);\n };\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n return await this.generateContentStreamInternal(params);\n };\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param model - The model to use.\n * @param prompt - A text description of the image to generate.\n * @param [config] - The config for image generation.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n };\n }\n return response;\n });\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n apiClient,\n chunk,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n apiClient,\n chunk,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.get({operation: operation});\n * }\n *\n * console.log(operation.result?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n async generateVideos(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function getOperationParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromMldev(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromMldev(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromVertex(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, ['response']);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromVertex(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_operations_converters';\nimport * as types from './types';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param operation The Operation object returned by a previous API call.\n * @return The updated Operation object, with the latest status or result.\n */\n async get(\n parameters: types.OperationGetParameters,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n var httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n return this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n } else {\n return this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n const body = converters.getOperationParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from '../_auth';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\n// TODO(b/395122533): We need a secure client side authentication mechanism.\nexport class WebAuth implements Auth {\n constructor(private readonly apiKey: string) {}\n\n async addAuthHeaders(headers: Headers): Promise {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuthOptions} from 'google-auth-library';\n\nimport {ApiClient} from './_api_client';\nimport {Caches} from './caches';\nimport {Chats} from './chats';\nimport {crossError} from './cross/_cross_error';\nimport {CrossUploader} from './cross/_cross_uploader';\nimport {CrossWebSocketFactory} from './cross/_cross_websocket';\nimport {Files} from './files';\nimport {Live} from './live';\nimport {Models} from './models';\nimport {Operations} from './operations';\nimport {HttpOptions} from './types';\nimport {WebAuth} from './web/_web_auth';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * Google Gen AI SDK's configuration options.\n *\n * See {@link GoogleGenAI} for usage samples.\n */\nexport interface GoogleGenAIOptions {\n /**\n * Optional. Determines whether to use the Vertex AI or the Gemini API.\n *\n * @remarks\n * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used.\n * When false, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} will be used.\n *\n * If unset, default SDK behavior is to use the Gemini API service.\n */\n vertexai?: boolean;\n /**\n * Optional. The Google Cloud project ID for Vertex AI clients.\n *\n * @remarks\n * Only supported on Node runtimes, ignored on browser runtimes.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project region for Vertex AI clients.\n *\n * @remarks\n * Only supported on Node runtimes, ignored on browser runtimes.\n *\n */\n location?: string;\n /**\n * The API Key, required for Gemini API clients.\n *\n * @remarks\n * Required on browser runtimes.\n */\n apiKey?: string;\n /**\n * Optional. The API version to use.\n *\n * @remarks\n * If unset, the default API version will be used.\n */\n apiVersion?: string;\n /**\n * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients.\n *\n * @remarks\n * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}.\n *\n * Only supported on Node runtimes, ignored on browser runtimes.\n *\n */\n googleAuthOptions?: GoogleAuthOptions;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n}\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API}\n * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set,\n * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n\n constructor(options: GoogleGenAIOptions) {\n if (options.apiKey == null) {\n throw new Error(\n `An API Key must be set when running in an unspecified environment.\\n + ${crossError().message}`,\n );\n }\n this.vertexai = options.vertexai ?? false;\n this.apiKey = options.apiKey;\n this.apiVersion = options.apiVersion;\n const auth = new WebAuth(this.apiKey);\n this.apiClient = new ApiClient({\n auth: auth,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross',\n uploader: new CrossUploader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory());\n this.chats = new Chats(this.models, this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n }\n}\n"],"names":["partToMldev","common.getValueByPath","common.setValueByPath","contentToMldev","functionDeclarationToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","toolToMldev","functionCallingConfigToMldev","toolConfigToMldev","t.tContents","t.tContent","t.tCachesModel","t.tCachedContentName","partToVertex","contentToVertex","schemaToVertex","functionDeclarationToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","toolToVertex","functionCallingConfigToVertex","toolConfigToVertex","converters.createCachedContentParametersToVertex","common.formatMap","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","t.tSchema","t.tTools","t.tTool","t.tSpeechConfig","t.tModel","t.tContentsForEmbed","t.tBytes","videoFromMldev","generatedVideoFromMldev","generateVideosResponseFromMldev","generateVideosOperationFromMldev","videoFromVertex","generatedVideoFromVertex","generateVideosResponseFromVertex","generateVideosOperationFromVertex","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","types.GenerateContentResponse","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex"],"mappings":"AAAA;;;;AAIG;MAIU,UAAU,CAAA;AAAG;AAWV,SAAA,SAAS,CACvB,cAAsB,EACtB,QAAiC,EAAA;;IAGjC,MAAM,KAAK,GAAG,cAAc;;IAG5B,OAAO,cAAc,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,GAAG,KAAI;AAClD,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC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CAAC,UAAU,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC;;AAEnD;;;;"} \ No newline at end of file diff --git a/node_modules/@google/genai/dist/node/index.js b/node_modules/@google/genai/dist/node/index.js new file mode 100644 index 0000000..51f5802 --- /dev/null +++ b/node_modules/@google/genai/dist/node/index.js @@ -0,0 +1,8195 @@ +'use strict'; + +var googleAuthLibrary = require('google-auth-library'); +var NodeWs = require('ws'); +var fs = require('fs/promises'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var NodeWs__namespace = /*#__PURE__*/_interopNamespaceDefault(NodeWs); +var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs); + +/** + * @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 { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + 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 undefined; + } + 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 undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @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 (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 tPart(apiClient, 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(apiClient, 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(apiClient, item)); + } + return [tPart(apiClient, 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 _isUserPart(origin) { + if (origin === null || origin === undefined) { + return false; + } + if (_isFunctionCallPart(origin)) { + return false; + } + return true; +} +function _areUserParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + return false; + } + return origin.every(_isUserPart); +} +function tContent(apiClient, origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // @ts-expect-error: _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + if (_isUserPart(origin)) { + return { + role: 'user', + parts: tParts(apiClient, origin), + }; + } + else { + return { + role: 'model', + parts: tParts(apiClient, origin), + }; + } +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(apiClient, 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(apiClient, 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(apiClient, item)); + } + return [tContent(apiClient, origin)]; +} +function _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts) { + if (accumulatedParts.length === 0) { + return; + } + if (_areUserParts(accumulatedParts)) { + result.push({ + role: 'user', + parts: tParts(apiClient, accumulatedParts), + }); + } + else { + result.push({ + role: 'model', + parts: tParts(apiClient, accumulatedParts), + }); + } + accumulatedParts.length = 0; // clear the array inplace +} +function _handleCurrentPart(apiClient, result, accumulatedParts, currentPart) { + if (_isUserPart(currentPart) === _areUserParts(accumulatedParts)) { + accumulatedParts.push(currentPart); + } + else { + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + accumulatedParts.length = 0; + accumulatedParts.push(currentPart); + } +} +function tContents(apiClient, origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + return [tContent(apiClient, origin)]; + } + const result = []; + const accumulatedParts = []; + for (const content of origin) { + if (_isContent(content)) { + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + // @ts-expect-error: content is a Content here + result.push(content); + } + else if (typeof content === 'string' || + (typeof content === 'object' && !Array.isArray(content))) { + // @ts-expect-error: content is a part here + _handleCurrentPart(apiClient, result, accumulatedParts, content); + } + else if (Array.isArray(content)) { + // if there're consecutive user parts before the list, + // convert to UserContent and append to result + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + result.push({ + role: 'user', + parts: tParts(apiClient, content), + }); + } + else { + throw new Error(`Unsupported content type: ${typeof content}`); + } + } + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + return result; +} +function processSchema(apiClient, schema) { + if (!apiClient.isVertexAI()) { + if ('default' in schema) { + throw new Error('Default value is not supported in the response schema for the Gemini API.'); + } + } + if ('anyOf' in schema) { + if (schema['anyOf'] !== undefined) { + for (const subSchema of schema['anyOf']) { + processSchema(apiClient, subSchema); + } + } + } + if ('items' in schema) { + if (schema['items'] !== undefined) { + processSchema(apiClient, schema['items']); + } + } + if ('properties' in schema) { + if (schema['properties'] !== undefined) { + for (const subSchema of Object.values(schema['properties'])) { + processSchema(apiClient, subSchema); + } + } + } +} +function tSchema(apiClient, schema) { + processSchema(apiClient, schema); + return schema; +} +function tSpeechConfig(apiClient, speechConfig) { + if (typeof speechConfig === 'object' && 'voiceConfig' in speechConfig) { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tTool(apiClient, tool) { + return tool; +} +function tTools(apiClient, tool) { + if (!Array.isArray(tool)) { + throw new Error('tool is required and must be an array of Tools'); + } + return tool; +} +/** + * 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 tBytes(apiClient, fromImageBytes) { + if (typeof fromImageBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromImageBytes; +} +function tFileName(apiClient, fromName) { + if (typeof fromName !== 'string') { + throw new Error('fromName must be a string'); + } + // Remove the files/ prefx for MLdev urls to get the actual name of the file. + if (fromName.startsWith('files/')) { + return fromName.split('files/')[1]; + } + return fromName; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function partToMldev$1(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['videoMetadata']) !== undefined) { + throw new Error('videoMetadata parameter is not supported in Gemini API.'); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$1(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['response']) !== undefined) { + throw new Error('response parameter is not supported in Gemini API.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToMldev$1() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(apiClient, 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) { + if (Array.isArray(fromContents)) { + setValueByPath(parentObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev$1(apiClient, item); + }))); + } + else { + setValueByPath(parentObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(apiClient, fromToolConfig)); + } + 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) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(apiClient, 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) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(apiClient, 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(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function functionDeclarationToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], schemaToVertex$1(apiClient, fromResponse)); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToVertex$1() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(apiClient, 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) { + if (Array.isArray(fromContents)) { + setValueByPath(parentObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex$1(apiClient, item); + }))); + } + else { + setValueByPath(parentObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$1(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(apiClient, fromToolConfig)); + } + 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) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(apiClient, 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 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) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(apiClient, 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 listCachedContentsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(apiClient, 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 fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + if (Array.isArray(fromCachedContents)) { + setValueByPath(toObject, ['cachedContents'], fromCachedContents.map((item) => { + return cachedContentFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['cachedContents'], fromCachedContents); + } + } + return toObject; +} +function cachedContentFromVertex(apiClient, 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 fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + if (Array.isArray(fromCachedContents)) { + setValueByPath(toObject, ['cachedContents'], fromCachedContents.map((item) => { + return cachedContentFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['cachedContents'], fromCachedContents); + } + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Pagers for the GenAI List APIs. + */ +exports.PagedItem = void 0; +(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"; +})(exports.PagedItem || (exports.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.idxInternal = 0; + let requestParams = { config: {} }; + if (!params) { + 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 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 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +exports.Outcome = void 0; +(function (Outcome) { + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(exports.Outcome || (exports.Outcome = {})); +exports.Language = void 0; +(function (Language) { + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + Language["PYTHON"] = "PYTHON"; +})(exports.Language || (exports.Language = {})); +exports.Type = void 0; +(function (Type) { + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + Type["STRING"] = "STRING"; + Type["NUMBER"] = "NUMBER"; + Type["INTEGER"] = "INTEGER"; + Type["BOOLEAN"] = "BOOLEAN"; + Type["ARRAY"] = "ARRAY"; + Type["OBJECT"] = "OBJECT"; +})(exports.Type || (exports.Type = {})); +exports.HarmCategory = void 0; +(function (HarmCategory) { + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; +})(exports.HarmCategory || (exports.HarmCategory = {})); +exports.HarmBlockMethod = void 0; +(function (HarmBlockMethod) { + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(exports.HarmBlockMethod || (exports.HarmBlockMethod = {})); +exports.HarmBlockThreshold = void 0; +(function (HarmBlockThreshold) { + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + HarmBlockThreshold["OFF"] = "OFF"; +})(exports.HarmBlockThreshold || (exports.HarmBlockThreshold = {})); +exports.Mode = void 0; +(function (Mode) { + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.Mode || (exports.Mode = {})); +exports.FinishReason = void 0; +(function (FinishReason) { + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + FinishReason["STOP"] = "STOP"; + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + FinishReason["SAFETY"] = "SAFETY"; + FinishReason["RECITATION"] = "RECITATION"; + FinishReason["OTHER"] = "OTHER"; + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + FinishReason["SPII"] = "SPII"; + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(exports.FinishReason || (exports.FinishReason = {})); +exports.HarmProbability = void 0; +(function (HarmProbability) { + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + HarmProbability["LOW"] = "LOW"; + HarmProbability["MEDIUM"] = "MEDIUM"; + HarmProbability["HIGH"] = "HIGH"; +})(exports.HarmProbability || (exports.HarmProbability = {})); +exports.HarmSeverity = void 0; +(function (HarmSeverity) { + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(exports.HarmSeverity || (exports.HarmSeverity = {})); +exports.BlockedReason = void 0; +(function (BlockedReason) { + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + BlockedReason["SAFETY"] = "SAFETY"; + BlockedReason["OTHER"] = "OTHER"; + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; +})(exports.BlockedReason || (exports.BlockedReason = {})); +exports.Modality = void 0; +(function (Modality) { + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + Modality["TEXT"] = "TEXT"; + Modality["IMAGE"] = "IMAGE"; + Modality["AUDIO"] = "AUDIO"; +})(exports.Modality || (exports.Modality = {})); +exports.State = void 0; +(function (State) { + State["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + State["ACTIVE"] = "ACTIVE"; + State["ERROR"] = "ERROR"; +})(exports.State || (exports.State = {})); +exports.DynamicRetrievalConfigMode = void 0; +(function (DynamicRetrievalConfigMode) { + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.DynamicRetrievalConfigMode || (exports.DynamicRetrievalConfigMode = {})); +exports.FunctionCallingConfigMode = void 0; +(function (FunctionCallingConfigMode) { + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + FunctionCallingConfigMode["AUTO"] = "AUTO"; + FunctionCallingConfigMode["ANY"] = "ANY"; + FunctionCallingConfigMode["NONE"] = "NONE"; +})(exports.FunctionCallingConfigMode || (exports.FunctionCallingConfigMode = {})); +exports.MediaResolution = void 0; +(function (MediaResolution) { + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(exports.MediaResolution || (exports.MediaResolution = {})); +exports.SafetyFilterLevel = void 0; +(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"; +})(exports.SafetyFilterLevel || (exports.SafetyFilterLevel = {})); +exports.PersonGeneration = void 0; +(function (PersonGeneration) { + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(exports.PersonGeneration || (exports.PersonGeneration = {})); +exports.ImagePromptLanguage = void 0; +(function (ImagePromptLanguage) { + ImagePromptLanguage["auto"] = "auto"; + ImagePromptLanguage["en"] = "en"; + ImagePromptLanguage["ja"] = "ja"; + ImagePromptLanguage["ko"] = "ko"; + ImagePromptLanguage["hi"] = "hi"; +})(exports.ImagePromptLanguage || (exports.ImagePromptLanguage = {})); +exports.FileState = void 0; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(exports.FileState || (exports.FileState = {})); +exports.FileSource = void 0; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(exports.FileSource || (exports.FileSource = {})); +exports.MaskReferenceMode = void 0; +(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"; +})(exports.MaskReferenceMode || (exports.MaskReferenceMode = {})); +exports.ControlReferenceType = void 0; +(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"; +})(exports.ControlReferenceType || (exports.ControlReferenceType = {})); +exports.SubjectReferenceType = void 0; +(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"; +})(exports.SubjectReferenceType || (exports.SubjectReferenceType = {})); +exports.MediaModality = void 0; +(function (MediaModality) { + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + MediaModality["TEXT"] = "TEXT"; + MediaModality["IMAGE"] = "IMAGE"; + MediaModality["VIDEO"] = "VIDEO"; + MediaModality["AUDIO"] = "AUDIO"; + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(exports.MediaModality || (exports.MediaModality = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * 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) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * 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), + }; +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +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' && + (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 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 counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** 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(); + } +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** 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 = []; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.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 [Vertex AI 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-1.5-flash', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + 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: 'gemini-1.5-flash'}); + * ``` + */ + async get(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + 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: 'gemini-1.5-flash'}); + * ``` + */ + async delete(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + 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: 'gemini-1.5-flash', + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(this.apiClient, 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 __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; + } + if (part.text !== undefined && part.text === '') { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @remarks + * Expects the history to start with a user turn and then alternate between + * user and model turns. + * + * @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; + } + if (history[0].role !== 'user') { + throw new Error('History must start with a user turn.'); + } + 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; + let userInput = comprehensiveHistory[0]; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + userInput = 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(userInput); + curatedHistory.push(...modelOutput); + } + } + } + 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, 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(this.apiClient, 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; + 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; + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput); + return; + })(); + await this.sendPromise; + 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(this.apiClient, 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, + }); + this.sendPromise = streamResponse.then(() => 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) { + return curated ? extractCuratedHistory(this.history) : this.history; + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.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 && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role === 'model')) { + 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: [], + }); + } + this.history.push(userInput); + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function listFilesConfigToMldev(apiClient, 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(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(apiClient, fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(apiClient, 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 fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(apiClient, fromError)); + } + return toObject; +} +function createFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(apiClient, fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(apiClient, 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 fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(apiClient, fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + if (Array.isArray(fromFiles)) { + setValueByPath(toObject, ['files'], fromFiles.map((item) => { + return fileFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['files'], fromFiles); + } + } + return toObject; +} +function createFileResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromHttpHeaders = getValueByPath(fromObject, ['httpHeaders']); + if (fromHttpHeaders != null) { + setValueByPath(toObject, ['httpHeaders'], fromHttpHeaders); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.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 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. + * Somex eamples 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 + * `common.UploadFileParameters` interface. + * @return A promise that resolves to a `types.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, + * 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('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(this.apiClient, response); + return file; + }); + } + async listInternal(params) { + var _a; + 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(this.apiClient, params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a; + 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(this.apiClient, params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(this.apiClient, 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; + 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(this.apiClient, params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(this.apiClient, apiResponse); + 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; + 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(this.apiClient, params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function partToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['videoMetadata']) !== undefined) { + throw new Error('videoMetadata parameter is not supported in Gemini API.'); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToMldev(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['example']) !== undefined) { + throw new Error('example parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['pattern']) !== undefined) { + throw new Error('pattern parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['default']) !== undefined) { + throw new Error('default parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['maxLength']) !== undefined) { + throw new Error('maxLength parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['minLength']) !== undefined) { + throw new Error('minLength parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['minProperties']) !== undefined) { + throw new Error('minProperties parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['maxProperties']) !== undefined) { + throw new Error('maxProperties parameter is not supported in Gemini API.'); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['response']) !== undefined) { + throw new Error('response parameter is not supported in Gemini API.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToMldev() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(apiClient, fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(apiClient, fromVoiceConfig)); + } + return toObject; +} +function thinkingConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev(apiClient, tContent(apiClient, 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'], schemaToMldev(apiClient, tSchema(apiClient, fromResponseSchema))); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + if (Array.isArray(fromSafetySettings)) { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings.map((item) => { + return safetySettingToMldev(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings); + } + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], tTools(apiClient, tTools(apiClient, fromTools).map((item) => { + return toolToMldev(apiClient, tTool(apiClient, item)); + }))); + } + else { + setValueByPath(parentObject, ['tools'], tTools(apiClient, fromTools)); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(apiClient, fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + 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'], speechConfigToMldev(apiClient, tSpeechConfig(apiClient, fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(apiClient, fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(apiClient, 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 not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + 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); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + 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); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function countTokensConfigToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(apiClient, fromConfig)); + } + return toObject; +} +function imageToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(apiClient, fromObject, parentObject) { + 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 not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + 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 not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + if (getValueByPath(fromObject, ['resolution']) !== undefined) { + throw new Error('resolution parameter is not supported in Gemini API.'); + } + 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 not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + 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(apiClient, fromImage)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToVertex(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(apiClient, fromObject) { + const toObject = {}; + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(apiClient, fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], schemaToVertex(apiClient, fromResponse)); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToVertex() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(apiClient, fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(apiClient, fromVoiceConfig)); + } + return toObject; +} +function thinkingConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(apiClient, tContent(apiClient, 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'], schemaToVertex(apiClient, tSchema(apiClient, fromResponseSchema))); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + if (Array.isArray(fromSafetySettings)) { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings.map((item) => { + return safetySettingToVertex(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings); + } + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], tTools(apiClient, tTools(apiClient, fromTools).map((item) => { + return toolToVertex(apiClient, tTool(apiClient, item)); + }))); + } + else { + setValueByPath(parentObject, ['tools'], tTools(apiClient, fromTools)); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(apiClient, 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(apiClient, tSpeechConfig(apiClient, fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(apiClient, fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(apiClient, fromObject, parentObject) { + 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 fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function countTokensConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToVertex(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function imageToVertex(apiClient, fromObject) { + 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(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToVertex(apiClient, fromObject, parentObject) { + 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); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + 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(apiClient, fromImage)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function candidateFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(apiClient, fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(apiClient, 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 fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + 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) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + if (Array.isArray(fromCandidates)) { + setValueByPath(toObject, ['candidates'], fromCandidates.map((item) => { + return candidateFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['candidates'], fromCandidates); + } + } + 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 fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + if (Array.isArray(fromEmbeddings)) { + setValueByPath(toObject, ['embeddings'], fromEmbeddings.map((item) => { + return contentEmbeddingFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['embeddings'], fromEmbeddings); + } + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(apiClient, fromObject) { + 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 generatedImageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(apiClient, fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(apiClient, fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + if (Array.isArray(fromGeneratedImages)) { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages.map((item) => { + return generatedImageFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages); + } + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(apiClient, fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function countTokensResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + 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 videoFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev$1(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromMldev$1(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromMldev$1(apiClient, fromResult)); + } + return toObject; +} +function partFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function candidateFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(apiClient, fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(apiClient, fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + 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) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + if (Array.isArray(fromCandidates)) { + setValueByPath(toObject, ['candidates'], fromCandidates.map((item) => { + return candidateFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['candidates'], fromCandidates); + } + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + 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 fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(apiClient, fromObject) { + 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); + } + return toObject; +} +function contentEmbeddingFromVertex(apiClient, fromObject) { + 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(apiClient, fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + if (Array.isArray(fromEmbeddings)) { + setValueByPath(toObject, ['embeddings'], fromEmbeddings.map((item) => { + return contentEmbeddingFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['embeddings'], fromEmbeddings); + } + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(apiClient, fromMetadata)); + } + return toObject; +} +function imageFromVertex(apiClient, fromObject) { + 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(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(apiClient, fromObject) { + 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 generatedImageFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(apiClient, 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(apiClient, fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + if (Array.isArray(fromGeneratedImages)) { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages.map((item) => { + return generatedImageFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages); + } + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(apiClient, fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function countTokensResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex$1(apiClient, 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(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex$1(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromVertex$1(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, ['response']); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromVertex$1(apiClient, fromResult)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Converters for live client. + */ +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig !== undefined && fromConfig !== null) { + setValueByPath(toObject, ['setup'], liveConnectConfigToMldev(apiClient, fromConfig)); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel !== undefined) { + setValueByPath(toObject, ['setup', 'model'], fromModel); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig !== undefined && fromConfig !== null) { + setValueByPath(toObject, ['setup'], liveConnectConfigToVertex(apiClient, fromConfig)); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel !== undefined) { + setValueByPath(toObject, ['setup', 'model'], fromModel); + } + return toObject; +} +function liveServerMessageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete !== undefined) { + setValueByPath(toObject, ['setupComplete'], fromSetupComplete); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent !== undefined && fromServerContent !== null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(apiClient, fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall !== undefined && fromToolCall !== null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(apiClient, fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation !== undefined && + fromToolCallCancellation !== null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(apiClient, fromToolCallCancellation)); + } + return toObject; +} +function liveServerMessageFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete !== undefined) { + setValueByPath(toObject, ['setupComplete'], fromSetupComplete); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent !== undefined && fromServerContent !== null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(apiClient, fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall !== undefined && fromToolCall !== null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(apiClient, fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation !== undefined && + fromToolCallCancellation !== null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(apiClient, fromToolCallCancellation)); + } + return toObject; +} +function liveConnectConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (fromGenerationConfig !== undefined) { + setValueByPath(toObject, ['generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities !== undefined) { + setValueByPath(toObject, ['generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig !== undefined) { + setValueByPath(toObject, ['generationConfig', 'speechConfig'], fromSpeechConfig); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) { + setValueByPath(toObject, ['systemInstruction'], contentToMldev(apiClient, fromSystemInstruction)); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (fromTools !== undefined && + fromTools !== null && + Array.isArray(fromTools)) { + setValueByPath(toObject, ['tools'], fromTools.map((item) => { + return toolToMldev(apiClient, item); + })); + } + return toObject; +} +function liveConnectConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (fromGenerationConfig !== undefined) { + setValueByPath(toObject, ['generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities !== undefined) { + setValueByPath(toObject, ['generationConfig', 'responseModalities'], fromResponseModalities); + } + else { + // Set default to AUDIO to align with MLDev API. + setValueByPath(toObject, ['generationConfig', 'responseModalities'], ['AUDIO']); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig !== undefined) { + setValueByPath(toObject, ['generationConfig', 'speechConfig'], fromSpeechConfig); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) { + setValueByPath(toObject, ['systemInstruction'], contentToVertex(apiClient, fromSystemInstruction)); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (fromTools !== undefined && + fromTools !== null && + Array.isArray(fromTools)) { + setValueByPath(toObject, ['tools'], fromTools.map((item) => { + return toolToVertex(apiClient, item); + })); + } + return toObject; +} +function liveServerContentFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn !== undefined && fromModelTurn !== null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev(apiClient, fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete !== undefined) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted !== undefined) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + return toObject; +} +function liveServerContentFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn !== undefined && fromModelTurn !== null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex(apiClient, fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete !== undefined) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted !== undefined) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + return toObject; +} +function functionCallFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId !== undefined) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs !== undefined) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName !== undefined) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function functionCallFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs !== undefined) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName !== undefined) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls !== undefined && + fromFunctionCalls !== null && + Array.isArray(fromFunctionCalls)) { + setValueByPath(toObject, ['functionCalls'], fromFunctionCalls.map((item) => { + return functionCallFromMldev(apiClient, item); + })); + } + return toObject; +} +function liveServerToolCallFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls !== undefined && + fromFunctionCalls !== null && + Array.isArray(fromFunctionCalls)) { + setValueByPath(toObject, ['functionCalls'], fromFunctionCalls.map((item) => { + return functionCallFromVertex(apiClient, item); + })); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds !== undefined) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds !== undefined) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} + +/** + * @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) { + let serverMessage; + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + if (apiClient.isVertexAI()) { + serverMessage = liveServerMessageFromVertex(apiClient, data); + } + else { + serverMessage = liveServerMessageFromMldev(apiClient, data); + } + 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; + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental + + @remarks + If using the Gemini API, Live is currently only supported behind API + version `v1alpha`. Ensure that the API version is set to `v1alpha` when + initializing the SDK if relying on the Gemini API. + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + 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; + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const headers = mapToHeaders(this.apiClient.getDefaultHeaders()); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateContent?key=${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; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(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(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(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + 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); + } + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } +} +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(apiClient, params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(apiClient, item)); + } + else { + contents = contents.map((item) => contentToMldev(apiClient, 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 }, + }; + } + tLiveClientRealtimeInput(apiClient, params) { + let clientMessage = {}; + if (!('media' in params) || !params.media) { + throw new Error(`Failed to convert realtime input "media", type: '${typeof params.media}'`); + } + // LiveClientRealtimeInput + clientMessage = { realtimeInput: { mediaChunks: [params.media] } }; + return clientMessage; + } + 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) { + if (params.media == null) { + throw new Error('Media is required.'); + } + const clientMessage = this.tLiveClientRealtimeInput(this.apiClient, 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 + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + 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 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI 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) => { + return await this.generateContentInternal(params); + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI 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) => { + return await this.generateContentStreamInternal(params); + }; + /** + * Generates an image based on a text description and configuration. + * + * @param model - The model to use. + * @param prompt - A text description of the image to generate. + * @param [config] - The config for image generation. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + 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, + }; + } + else { + response = { + generatedImages: generatedImages, + }; + } + return response; + }); + }; + } + async generateContentInternal(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(this.apiClient, 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b; + 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['config']; + 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, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_1, _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(apiClient, chunk); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _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(apiClient, chunk); + 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_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_2) throw e_2.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 embedContent(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * 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 ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new GenerateImagesResponse(); + 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; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(this.apiClient, 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(this.apiClient, 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; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * 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', + * 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.get({operation: operation}); + * } + * + * console.log(operation.result?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideos(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex$1(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev$1(this.apiClient, apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function getOperationParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(apiClient, 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); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromMldev(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromMldev(apiClient, fromResult)); + } + return toObject; +} +function videoFromVertex(apiClient, 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(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromVertex(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, ['response']); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromVertex(apiClient, fromResult)); + } + return toObject; +} + +/** + * @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 operation The Operation object returned by a previous API call. + * @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]; + var httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + return this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + } + else { + return this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(this.apiClient, params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = getOperationParametersToMldev(this.apiClient, params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(this.apiClient, apiResponse); + return resp; + }); + } + } + async fetchPredictVideosOperationInternal(params) { + var _a; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(this.apiClient, params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '0.7.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 responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * Client errors raised by the GenAI API. + */ +class ClientError extends Error { + constructor(message, stackTrace) { + if (stackTrace) { + super(message, { cause: stackTrace }); + } + else { + super(message, { cause: new Error().stack }); + } + this.message = message; + this.name = 'ClientError'; + } +} +/** + * Server errors raised by the GenAI API. + */ +class ServerError extends Error { + constructor(message, stackTrace) { + if (stackTrace) { + super(message, { cause: stackTrace }); + } + else { + super(message, { cause: new Error().stack }); + } + this.message = message; + this.name = 'ServerError'; + } +} +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + // Assume that proj/api key validation occurs before they are passed in. + if (this.getProject() || this.getLocation()) { + initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + this.clientOptions.apiKey = undefined; // unset API key. + } + else { + initHttpOptions.baseUrl = `https://aiplatform.googleapis.com/`; + this.clientOptions.project = undefined; // unset project. + this.clientOptions.location = undefined; // unset location. + } + } + else { + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : 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; + } + 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 = '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) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (this.clientOptions.vertexai && + !this.clientOptions.apiKey && + !path.startsWith('projects/')) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const url = this.constructUrl(request.path, patchedHttpOptions); + 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); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + 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 url = this.constructUrl(request.path, patchedHttpOptions); + 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); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions) { + if (httpOptions && httpOptions.timeout && httpOptions.timeout > 0) { + const abortController = new AbortController(); + const signal = abortController.signal; + setTimeout(() => abortController.abort(), httpOptions.timeout); + requestInit.signal = signal; + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + 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 = ''; + 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); + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const chunkData = JSON.parse(processedChunkString); + yield yield __await(chunkData); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + 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) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * 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 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 uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + 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 ServerError('response is undefined'); + } + if (!response.ok) { + const status = response.status; + const statusText = response.statusText; + 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: 'exception parsing response', + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = `got status: ${status} ${statusText}. ${JSON.stringify(errorBody)}`; + if (status >= 400 && status < 500) { + const clientError = new ClientError(errorMessage); + throw clientError; + } + else if (status >= 500 && status < 600) { + const serverError = new ServerError(errorMessage); + throw serverError; + } + throw new Error(errorMessage); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +const AUTHORIZATION_HEADER = 'Authorization'; +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 googleAuthLibrary.GoogleAuth(vertexAuthOptions); + } + async addAuthHeaders(headers) { + if (this.apiKey !== undefined) { + this.addKeyHeader(headers); + return; + } + return this.addGoogleAuthHeaders(headers); + } + 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) { + if (headers.get(AUTHORIZATION_HEADER) !== null) { + return; + } + 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 token = await this.googleAuth.getAccessToken(); + headers.append(AUTHORIZATION_HEADER, `Bearer ${token}`); + } +} +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 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 NodeWs__namespace.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(); + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b; + 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'; + } + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-status']) !== '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.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b['x-goog-upload-status']) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} + +/** + * @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 fs__namespace.stat(file); + fileStat.size = originalStat.size; + fileStat.type = this.inferMimeType(file); + return fileStat; + } + else { + return await getBlobStat(file); + } + } + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + return await this.uploadFileFromPath(file, uploadUrl, apiClient); + } + else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + /** + * 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) { + var _a, _b; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + let fileHandle; + try { + fileHandle = await fs__namespace.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]); + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(bytesRead), + }, + }, + }); + offset += bytesRead; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-status']) !== 'active') { + break; + } + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b['x-goog-upload-status']) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; + } + finally { + // Ensure the file handle is always closed + if (fileHandle) { + await fileHandle.close(); + } + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * 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 { + constructor(options) { + var _a, _b, _c, _d, _e; + // Validate explicitly set initializer values. + if ((options.project || options.location) && options.apiKey) { + throw new Error('Project/location and API key are mutually exclusive in the client initializer.'); + } + this.vertexai = + (_b = (_a = options.vertexai) !== null && _a !== void 0 ? _a : getBooleanEnv('GOOGLE_GENAI_USE_VERTEXAI')) !== null && _b !== void 0 ? _b : false; + const envApiKey = getEnv('GOOGLE_API_KEY'); + const envProject = getEnv('GOOGLE_CLOUD_PROJECT'); + const envLocation = getEnv('GOOGLE_CLOUD_LOCATION'); + this.apiKey = (_c = options.apiKey) !== null && _c !== void 0 ? _c : envApiKey; + this.project = (_d = options.project) !== null && _d !== void 0 ? _d : envProject; + this.location = (_e = options.location) !== null && _e !== void 0 ? _e : envLocation; + // Handle when to use Vertex AI in express mode (api key) + if (options.vertexai) { + // Explicit api_key and explicit project/location already handled above. + if ((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) && 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 ((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; + } + } + this.apiVersion = options.apiVersion; + 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: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version, + uploader: new NodeUploader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory()); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(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 getBooleanEnv(env) { + return stringToBoolean(getEnv(env)); +} +function stringToBoolean(str) { + if (str === undefined) { + return false; + } + return str.toLowerCase() === 'true'; +} + +exports.Caches = Caches; +exports.Chat = Chat; +exports.Chats = Chats; +exports.ComputeTokensResponse = ComputeTokensResponse; +exports.CountTokensResponse = CountTokensResponse; +exports.CreateFileResponse = CreateFileResponse; +exports.DeleteCachedContentResponse = DeleteCachedContentResponse; +exports.DeleteFileResponse = DeleteFileResponse; +exports.EmbedContentResponse = EmbedContentResponse; +exports.Files = Files; +exports.FunctionResponse = FunctionResponse; +exports.GenerateContentResponse = GenerateContentResponse; +exports.GenerateContentResponsePromptFeedback = GenerateContentResponsePromptFeedback; +exports.GenerateContentResponseUsageMetadata = GenerateContentResponseUsageMetadata; +exports.GenerateImagesResponse = GenerateImagesResponse; +exports.GenerateVideosResponse = GenerateVideosResponse; +exports.GoogleGenAI = GoogleGenAI; +exports.HttpResponse = HttpResponse; +exports.ListCachedContentsResponse = ListCachedContentsResponse; +exports.ListFilesResponse = ListFilesResponse; +exports.Live = Live; +exports.LiveClientToolResponse = LiveClientToolResponse; +exports.LiveSendToolResponseParameters = LiveSendToolResponseParameters; +exports.Models = Models; +exports.Operations = Operations; +exports.Pager = Pager; +exports.ReplayResponse = ReplayResponse; +exports.Session = Session; +exports.createModelContent = createModelContent; +exports.createPartFromBase64 = createPartFromBase64; +exports.createPartFromCodeExecutionResult = createPartFromCodeExecutionResult; +exports.createPartFromExecutableCode = createPartFromExecutableCode; +exports.createPartFromFunctionCall = createPartFromFunctionCall; +exports.createPartFromFunctionResponse = createPartFromFunctionResponse; +exports.createPartFromText = createPartFromText; +exports.createPartFromUri = createPartFromUri; +exports.createUserContent = createUserContent; +//# sourceMappingURL=index.js.map diff --git a/node_modules/@google/genai/dist/node/index.js.map b/node_modules/@google/genai/dist/node/index.js.map new file mode 100644 index 0000000..f4d80e2 --- /dev/null +++ b/node_modules/@google/genai/dist/node/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../../src/_common.ts","../../src/_transformers.ts","../../src/converters/_caches_converters.ts","../../src/pagers.ts","../../src/types.ts","../../src/caches.ts","../../src/chats.ts","../../src/converters/_files_converters.ts","../../src/files.ts","../../src/converters/_models_converters.ts","../../src/converters/_live_converters.ts","../../src/live.ts","../../src/models.ts","../../src/converters/_operations_converters.ts","../../src/operations.ts","../../src/_api_client.ts","../../src/node/_node_auth.ts","../../src/node/_node_websocket.ts","../../src/cross/_cross_uploader.ts","../../src/node/_node_uploader.ts","../../src/node/node_client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {UploadFileConfig} from './types';\n\nexport class BaseModule {}\n\n// TODO (b/406332263): Move this to a place where it can be linked for doc.\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client';\nimport * as types from './types';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tPart(\n apiClient: ApiClient,\n origin?: types.PartUnion | null,\n): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(\n apiClient: ApiClient,\n origin?: types.PartListUnion | null,\n): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(apiClient, item as types.PartUnion)!);\n }\n return [tPart(apiClient, origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isUserPart(origin: unknown): boolean {\n if (origin === null || origin === undefined) {\n return false;\n }\n if (_isFunctionCallPart(origin)) {\n return false;\n }\n return true;\n}\n\nfunction _areUserParts(origin: types.PartListUnion[]): boolean {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n return false;\n }\n return origin.every(_isUserPart);\n}\n\nexport function tContent(\n apiClient: ApiClient,\n origin?: types.ContentUnion,\n): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // @ts-expect-error: _isContent is a utility function that checks if the\n // origin is a Content.\n return origin;\n }\n\n if (_isUserPart(origin)) {\n return {\n role: 'user',\n parts: tParts(apiClient, origin as types.PartListUnion)!,\n };\n } else {\n return {\n role: 'model',\n parts: tParts(apiClient, origin as types.PartListUnion)!,\n };\n }\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(apiClient, item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(apiClient, origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map(\n (item) => tContent(apiClient, item as types.ContentUnion)!,\n );\n }\n return [tContent(apiClient, origin as types.ContentUnion)!];\n}\n\nfunction _appendAccumulatedPartsAsContent(\n apiClient: ApiClient,\n result: types.Content[],\n accumulatedParts: types.PartUnion[],\n) {\n if (accumulatedParts.length === 0) {\n return;\n }\n if (_areUserParts(accumulatedParts)) {\n result.push({\n role: 'user',\n parts: tParts(apiClient, accumulatedParts),\n });\n } else {\n result.push({\n role: 'model',\n parts: tParts(apiClient, accumulatedParts),\n });\n }\n accumulatedParts.length = 0; // clear the array inplace\n}\n\nfunction _handleCurrentPart(\n apiClient: ApiClient,\n result: types.Content[],\n accumulatedParts: types.PartUnion[],\n currentPart: types.PartUnion,\n) {\n if (_isUserPart(currentPart) === _areUserParts(accumulatedParts)) {\n accumulatedParts.push(currentPart);\n } else {\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n accumulatedParts.length = 0;\n accumulatedParts.push(currentPart);\n }\n}\n\nexport function tContents(\n apiClient: ApiClient,\n origin?: types.ContentListUnion,\n): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n return [tContent(apiClient, origin)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n\n for (const content of origin) {\n if (_isContent(content)) {\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n // @ts-expect-error: content is a Content here\n result.push(content);\n } else if (\n typeof content === 'string' ||\n (typeof content === 'object' && !Array.isArray(content))\n ) {\n // @ts-expect-error: content is a part here\n _handleCurrentPart(apiClient, result, accumulatedParts, content);\n } else if (Array.isArray(content)) {\n // if there're consecutive user parts before the list,\n // convert to UserContent and append to result\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n result.push({\n role: 'user',\n parts: tParts(apiClient, content),\n });\n } else {\n throw new Error(`Unsupported content type: ${typeof content}`);\n }\n }\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n\n return result;\n}\n\nexport function processSchema(apiClient: ApiClient, schema: types.Schema) {\n if (!apiClient.isVertexAI()) {\n if ('default' in schema) {\n throw new Error(\n 'Default value is not supported in the response schema for the Gemini API.',\n );\n }\n }\n\n if ('anyOf' in schema) {\n if (schema['anyOf'] !== undefined) {\n for (const subSchema of schema['anyOf']) {\n processSchema(apiClient, subSchema);\n }\n }\n }\n\n if ('items' in schema) {\n if (schema['items'] !== undefined) {\n processSchema(apiClient, schema['items']);\n }\n }\n\n if ('properties' in schema) {\n if (schema['properties'] !== undefined) {\n for (const subSchema of Object.values(schema['properties'])) {\n processSchema(apiClient, subSchema);\n }\n }\n }\n}\n\nexport function tSchema(\n apiClient: ApiClient,\n schema: types.Schema,\n): types.Schema {\n processSchema(apiClient, schema);\n return schema;\n}\n\nexport function tSpeechConfig(\n apiClient: ApiClient,\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object' && 'voiceConfig' in speechConfig) {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tTool(apiClient: ApiClient, tool: types.Tool): types.Tool {\n return tool;\n}\n\nexport function tTools(\n apiClient: ApiClient,\n tool: types.Tool[] | unknown,\n): types.Tool[] {\n if (!Array.isArray(tool)) {\n throw new Error('tool is required and must be an array of Tools');\n }\n return tool;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(\n apiClient: ApiClient,\n status: string | unknown,\n): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(\n apiClient: ApiClient,\n fromImageBytes: string | unknown,\n): string {\n if (typeof fromImageBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromImageBytes;\n}\nexport function tFileName(\n apiClient: ApiClient,\n fromName: string | unknown,\n): string {\n if (typeof fromName !== 'string') {\n throw new Error('fromName must be a string');\n }\n // Remove the files/ prefx for MLdev urls to get the actual name of the file.\n if (fromName.startsWith('files/')) {\n return fromName.split('files/')[1];\n }\n return fromName;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function partToMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['videoMetadata']) !== undefined) {\n throw new Error('videoMetadata parameter is not supported in Gemini API.');\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['example']) !== undefined) {\n throw new Error('example parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['pattern']) !== undefined) {\n throw new Error('pattern parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['default']) !== undefined) {\n throw new Error('default parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxLength']) !== undefined) {\n throw new Error('maxLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minLength']) !== undefined) {\n throw new Error('minLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minProperties']) !== undefined) {\n throw new Error('minProperties parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxProperties']) !== undefined) {\n throw new Error('maxProperties parameter is not supported in Gemini API.');\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['response']) !== undefined) {\n throw new Error('response parameter is not supported in Gemini API.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToMldev(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToMldev());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(apiClient, fromToolConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partToVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n schemaToVertex(apiClient, fromResponse),\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToVertex(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToVertex());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(apiClient, fromToolConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n apiClient: ApiClient,\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n if (Array.isArray(fromCachedContents)) {\n common.setValueByPath(\n toObject,\n ['cachedContents'],\n fromCachedContents.map((item) => {\n return cachedContentFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['cachedContents'], fromCachedContents);\n }\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n apiClient: ApiClient,\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n if (Array.isArray(fromCachedContents)) {\n common.setValueByPath(\n toObject,\n ['cachedContents'],\n fromCachedContents.map((item) => {\n return cachedContentFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['cachedContents'], fromCachedContents);\n }\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nexport enum Outcome {\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n OUTCOME_OK = 'OUTCOME_OK',\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\nexport enum Language {\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n PYTHON = 'PYTHON',\n}\n\nexport enum Type {\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n STRING = 'STRING',\n NUMBER = 'NUMBER',\n INTEGER = 'INTEGER',\n BOOLEAN = 'BOOLEAN',\n ARRAY = 'ARRAY',\n OBJECT = 'OBJECT',\n}\n\nexport enum HarmCategory {\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n}\n\nexport enum HarmBlockMethod {\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n SEVERITY = 'SEVERITY',\n PROBABILITY = 'PROBABILITY',\n}\n\nexport enum HarmBlockThreshold {\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n OFF = 'OFF',\n}\n\nexport enum Mode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\nexport enum FinishReason {\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n STOP = 'STOP',\n MAX_TOKENS = 'MAX_TOKENS',\n SAFETY = 'SAFETY',\n RECITATION = 'RECITATION',\n OTHER = 'OTHER',\n BLOCKLIST = 'BLOCKLIST',\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n SPII = 'SPII',\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\nexport enum HarmProbability {\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n NEGLIGIBLE = 'NEGLIGIBLE',\n LOW = 'LOW',\n MEDIUM = 'MEDIUM',\n HIGH = 'HIGH',\n}\n\nexport enum HarmSeverity {\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\nexport enum BlockedReason {\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n SAFETY = 'SAFETY',\n OTHER = 'OTHER',\n BLOCKLIST = 'BLOCKLIST',\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n}\n\nexport enum Modality {\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n TEXT = 'TEXT',\n IMAGE = 'IMAGE',\n AUDIO = 'AUDIO',\n}\n\nexport enum State {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n ACTIVE = 'ACTIVE',\n ERROR = 'ERROR',\n}\n\nexport enum DynamicRetrievalConfigMode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\nexport enum FunctionCallingConfigMode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n AUTO = 'AUTO',\n ANY = 'ANY',\n NONE = 'NONE',\n}\n\nexport enum MediaResolution {\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\nexport enum PersonGeneration {\n DONT_ALLOW = 'DONT_ALLOW',\n ALLOW_ADULT = 'ALLOW_ADULT',\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\nexport enum ImagePromptLanguage {\n auto = 'auto',\n en = 'en',\n ja = 'ja',\n ko = 'ko',\n hi = 'hi',\n}\n\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\nexport enum MediaModality {\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n TEXT = 'TEXT',\n IMAGE = 'IMAGE',\n VIDEO = 'VIDEO',\n AUDIO = 'AUDIO',\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Metadata describes the input video content. */\nexport declare interface VideoMetadata {\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [FunctionDeclaration] tool and [FunctionCallingConfig] mode is set to [Mode.CODE]. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. Required. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** The id of the function call this response is for. Populated by the client\n to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Required. Raw bytes. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n left blank or unset. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n}\n\n/** Schema that defines the format of input and output data.\n\n Represents a select subset of an OpenAPI 3.0 schema object.\n */\nexport declare interface Schema {\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Describes the output from the function in the OpenAPI JSON Schema\n Object format. */\n response?: Schema;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. This field is only used by the Gemini Developer API services. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use.\n */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. e.g. 'gemini-1.5-pro-001'. */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response media type of the generated candidate text.\n */\n responseMimeType?: string;\n /** Schema that the generated candidate text must adhere to.\n */\n responseSchema?: SchemaUnion;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. This list must have the same size as the grounding_chunk_indices. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** Identifier for each response.\n */\n responseId?: string;\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `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.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport /** Optional parameters for the embed_content method. */\ndeclare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images.\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** Whether to use the prompt rewriting logic.\n */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both.\n */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories.\n */\n categories?: string[];\n /** List of scores of each categories.\n */\n scores?: number[];\n /** Internal use only.\n */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data.\n */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response.\n */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content.\n */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled.\n */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** List of generated images.\n */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True.\n */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional. Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 1280x720, 1920x1080 are supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation progress. */\n pubsubTopic?: string;\n /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** Class that represents the parameters for generating an image. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos. Optional for image to video use cases. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt is provided. */\n image?: Image;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes. */\n videoBytes?: string;\n /** Video encoding, for example \"video/mp4\". */\n mimeType?: string;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** A video generation operation. */\nexport declare interface GenerateVideosOperation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The normal response of the operation in case of success. */\n response?: Record;\n /** The generated videos. */\n result?: GenerateVideosResponse;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-1.5-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n onopen?: (() => void) | null;\n onmessage: (e: LiveServerMessage) => void;\n onerror?: ((e: ErrorEvent) => void) | null;\n onclose?: ((e: CloseEvent) => void) | null;\n}\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression if the ``output_mime_type`` is\n ``image/jpeg``. */\n outputCompressionQuality?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport declare interface RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport declare interface MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport declare interface ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport declare interface StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport declare interface SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n}\n\n/** Sent in response to a `LiveGenerateContentSetup` message from the client. */\nexport declare interface LiveServerSetupComplete {}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Response message for API call. */\nexport declare interface LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n\nThe following fields are supported:\n- `response_logprobs`\n- `response_mime_type`\n- `logprobs`\n- `response_schema`\n- `stop_sequence`\n- `routing_config`\n- `audio_timestamp`\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: Content;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** User input that is sent in real time.\n\n This is different from `ClientContentUpdate` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `ClientContentUpdate` and the `RealtimeUpdate`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: Content;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-1.5-pro', etc. See gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media: Blob;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters {\n /** The operation to be retrieved. */\n operation: GenerateVideosOperation;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = ContentUnion[] | ContentUnion;\n\nexport type SchemaUnion = Schema;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolListUnion = Tool[];\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_caches_converters';\nimport {PagedItem, Pager} from './pagers';\nimport * as types from './types';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference] (https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference] (https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-1.5-flash',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: 'gemini-1.5-flash'});\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: 'gemini-1.5-flash'});\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromVertex();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromMldev();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: 'gemini-1.5-flash',\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listCachedContentsResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listCachedContentsResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client';\nimport * as t from './_transformers';\nimport {Models} from './models';\nimport * as types from './types';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\n if (content.parts === undefined || content.parts.length === 0) {\n return false;\n }\n for (const part of content.parts) {\n if (part === undefined || Object.keys(part).length === 0) {\n return false;\n }\n if (part.text !== undefined && part.text === '') {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @remarks\n * Expects the history to start with a user turn and then alternate between\n * user and model turns.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n if (history[0].role !== 'user') {\n throw new Error('History must start with a user turn.');\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n let userInput = comprehensiveHistory[0];\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n userInput = comprehensiveHistory[i];\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(userInput);\n curatedHistory.push(...modelOutput);\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n params.history,\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(this.apiClient, params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(inputContent, modelOutput);\n return;\n })();\n await this.sendPromise;\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(this.apiClient, params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = streamResponse.then(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n return curated ? extractCuratedHistory(this.history) : this.history;\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role === 'model')\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n this.history.push(userInput);\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function listFilesConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n apiClient: ApiClient,\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(\n apiClient: ApiClient,\n fromObject: types.File,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(\n toObject,\n ['error'],\n fileStatusToMldev(apiClient, fromError),\n );\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(apiClient, fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'file'],\n t.tFileName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'file'],\n t.tFileName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n apiClient: ApiClient,\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(\n apiClient: ApiClient,\n fromObject: types.File,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(\n toObject,\n ['error'],\n fileStatusFromMldev(apiClient, fromError),\n );\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n if (Array.isArray(fromFiles)) {\n common.setValueByPath(\n toObject,\n ['files'],\n fromFiles.map((item) => {\n return fileFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['files'], fromFiles);\n }\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromHttpHeaders = common.getValueByPath(fromObject, ['httpHeaders']);\n if (fromHttpHeaders != null) {\n common.setValueByPath(toObject, ['httpHeaders'], fromHttpHeaders);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_files_converters';\nimport {PagedItem, Pager} from './pagers';\nimport * as types from './types';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `common.UploadFileParameters` interface.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: common.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(this.apiClient, response);\n return file as types.File;\n });\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(this.apiClient, apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteFileResponseFromMldev();\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function partToMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['videoMetadata']) !== undefined) {\n throw new Error('videoMetadata parameter is not supported in Gemini API.');\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['example']) !== undefined) {\n throw new Error('example parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['pattern']) !== undefined) {\n throw new Error('pattern parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['default']) !== undefined) {\n throw new Error('default parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxLength']) !== undefined) {\n throw new Error('maxLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minLength']) !== undefined) {\n throw new Error('minLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minProperties']) !== undefined) {\n throw new Error('minProperties parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxProperties']) !== undefined) {\n throw new Error('maxProperties parameter is not supported in Gemini API.');\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n apiClient: ApiClient,\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['response']) !== undefined) {\n throw new Error('response parameter is not supported in Gemini API.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToMldev(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToMldev());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(apiClient, fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(apiClient, fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(apiClient, t.tSchema(apiClient, fromResponseSchema)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n if (Array.isArray(fromSafetySettings)) {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings.map((item) => {\n return safetySettingToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings,\n );\n }\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(\n apiClient,\n t.tTools(apiClient, fromTools).map((item) => {\n return toolToMldev(apiClient, t.tTool(apiClient, item));\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(apiClient, fromTools),\n );\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(apiClient, fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(\n apiClient,\n t.tSpeechConfig(apiClient, fromSpeechConfig),\n ),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(apiClient, fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(apiClient, fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n if (common.getValueByPath(fromObject, ['resolution']) !== undefined) {\n throw new Error('resolution parameter is not supported in Gemini API.');\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(apiClient, fromImage),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partToVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n apiClient: ApiClient,\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n schemaToVertex(apiClient, fromResponse),\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToVertex(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToVertex());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(apiClient, fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(apiClient, fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(apiClient, t.tSchema(apiClient, fromResponseSchema)),\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n if (Array.isArray(fromSafetySettings)) {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings.map((item) => {\n return safetySettingToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings,\n );\n }\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(\n apiClient,\n t.tTools(apiClient, fromTools).map((item) => {\n return toolToVertex(apiClient, t.tTool(apiClient, item));\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(apiClient, fromTools),\n );\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(apiClient, fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(\n apiClient,\n t.tSpeechConfig(apiClient, fromSpeechConfig),\n ),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(apiClient, fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(apiClient, fromImage),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partFromMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n apiClient: ApiClient,\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n apiClient: ApiClient,\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromMldev(apiClient, fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(apiClient, fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n if (Array.isArray(fromCandidates)) {\n common.setValueByPath(\n toObject,\n ['candidates'],\n fromCandidates.map((item) => {\n return candidateFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['candidates'], fromCandidates);\n }\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n apiClient: ApiClient,\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n if (Array.isArray(fromEmbeddings)) {\n common.setValueByPath(\n toObject,\n ['embeddings'],\n fromEmbeddings.map((item) => {\n return contentEmbeddingFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['embeddings'], fromEmbeddings);\n }\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['imageBytes'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n apiClient: ApiClient,\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['image'],\n imageFromMldev(apiClient, fromImage),\n );\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(apiClient, fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n if (Array.isArray(fromGeneratedImages)) {\n common.setValueByPath(\n toObject,\n ['generatedImages'],\n fromGeneratedImages.map((item) => {\n return generatedImageFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedImages'], fromGeneratedImages);\n }\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(apiClient, fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromMldev(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromMldev(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n apiClient: ApiClient,\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n apiClient: ApiClient,\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(apiClient, fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(apiClient, fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n if (Array.isArray(fromCandidates)) {\n common.setValueByPath(\n toObject,\n ['candidates'],\n fromCandidates.map((item) => {\n return candidateFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['candidates'], fromCandidates);\n }\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n apiClient: ApiClient,\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n apiClient: ApiClient,\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(apiClient, fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n if (Array.isArray(fromEmbeddings)) {\n common.setValueByPath(\n toObject,\n ['embeddings'],\n fromEmbeddings.map((item) => {\n return contentEmbeddingFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['embeddings'], fromEmbeddings);\n }\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(apiClient, fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['imageBytes'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n apiClient: ApiClient,\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['image'],\n imageFromVertex(apiClient, fromImage),\n );\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(apiClient, fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n if (Array.isArray(fromGeneratedImages)) {\n common.setValueByPath(\n toObject,\n ['generatedImages'],\n fromGeneratedImages.map((item) => {\n return generatedImageFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedImages'], fromGeneratedImages);\n }\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(apiClient, fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromVertex(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, ['response']);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromVertex(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as types from '../types';\nimport {\n contentFromMldev,\n contentFromVertex,\n contentToMldev,\n contentToVertex,\n toolToMldev,\n toolToVertex,\n} from './_models_converters';\n\n/**\n * Converters for live client.\n */\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): types.LiveClientMessage {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig !== undefined && fromConfig !== null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveConnectConfigToMldev(apiClient, fromConfig),\n );\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel !== undefined) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): types.LiveClientMessage {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig !== undefined && fromConfig !== null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveConnectConfigToVertex(apiClient, fromConfig),\n );\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel !== undefined) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerMessage,\n): types.LiveServerMessage {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete !== undefined) {\n common.setValueByPath(toObject, ['setupComplete'], fromSetupComplete);\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent !== undefined && fromServerContent !== null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(apiClient, fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall !== undefined && fromToolCall !== null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(apiClient, fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (\n fromToolCallCancellation !== undefined &&\n fromToolCallCancellation !== null\n ) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(\n apiClient,\n fromToolCallCancellation,\n ),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerMessage,\n): types.LiveServerMessage {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete !== undefined) {\n common.setValueByPath(toObject, ['setupComplete'], fromSetupComplete);\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent !== undefined && fromServerContent !== null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(apiClient, fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall !== undefined && fromToolCall !== null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(apiClient, fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (\n fromToolCallCancellation !== undefined &&\n fromToolCallCancellation !== null\n ) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(\n apiClient,\n fromToolCallCancellation,\n ),\n );\n }\n\n return toObject;\n}\n\nfunction liveConnectConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConfig,\n): types.LiveClientSetup {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig !== undefined) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'speechConfig'],\n fromSpeechConfig,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(apiClient, fromSystemInstruction),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (\n fromTools !== undefined &&\n fromTools !== null &&\n Array.isArray(fromTools)\n ) {\n common.setValueByPath(\n toObject,\n ['tools'],\n fromTools.map((item: types.Tool) => {\n return toolToMldev(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveConnectConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConfig,\n): types.LiveClientSetup {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig !== undefined) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n } else {\n // Set default to AUDIO to align with MLDev API.\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n ['AUDIO'],\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'speechConfig'],\n fromSpeechConfig,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(apiClient, fromSystemInstruction),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (\n fromTools !== undefined &&\n fromTools !== null &&\n Array.isArray(fromTools)\n ) {\n common.setValueByPath(\n toObject,\n ['tools'],\n fromTools.map((item: types.Tool) => {\n return toolToVertex(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerContentFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerContent,\n): types.LiveServerContent {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn !== undefined && fromModelTurn !== null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(apiClient, fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete !== undefined) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted !== undefined) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n return toObject;\n}\n\nfunction liveServerContentFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerContent,\n): types.LiveServerContent {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn !== undefined && fromModelTurn !== null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(apiClient, fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete !== undefined) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted !== undefined) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n return toObject;\n}\n\nfunction functionCallFromMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCall,\n): types.FunctionCall {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId !== undefined) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs !== undefined) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName !== undefined) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nfunction functionCallFromVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCall,\n): types.FunctionCall {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs !== undefined) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName !== undefined) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCall,\n): types.LiveServerToolCall {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (\n fromFunctionCalls !== undefined &&\n fromFunctionCalls !== null &&\n Array.isArray(fromFunctionCalls)\n ) {\n common.setValueByPath(\n toObject,\n ['functionCalls'],\n fromFunctionCalls.map((item: types.FunctionCall) => {\n return functionCallFromMldev(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCall,\n): types.LiveServerToolCall {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (\n fromFunctionCalls !== undefined &&\n fromFunctionCalls !== null &&\n Array.isArray(fromFunctionCalls)\n ) {\n common.setValueByPath(\n toObject,\n ['functionCalls'],\n fromFunctionCalls.map((item: types.FunctionCall) => {\n return functionCallFromVertex(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallCancellationFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCallCancellation,\n): types.LiveServerToolCallCancellation {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds !== undefined) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallCancellationFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCallCancellation,\n): types.LiveServerToolCallCancellation {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds !== undefined) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client';\nimport {Auth} from './_auth';\nimport * as t from './_transformers';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket';\nimport * as converters from './converters/_live_converters';\nimport {contentToMldev, contentToVertex} from './converters/_models_converters';\nimport * as types from './types';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n let serverMessage: types.LiveServerMessage;\n let data: types.LiveServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveServerMessage;\n }\n if (apiClient.isVertexAI()) {\n serverMessage = converters.liveServerMessageFromVertex(apiClient, data);\n } else {\n serverMessage = converters.liveServerMessageFromMldev(apiClient, data);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental\n\n @remarks\n If using the Gemini API, Live is currently only supported behind API\n version `v1alpha`. Ensure that the API version is set to `v1alpha` when\n initializing the SDK if relying on the Gemini API.\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n const session = await ai.live.connect({\n model: 'gemini-2.0-flash-exp',\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateContent?key=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: types.LiveClientMessage = {};\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(\n apiClient,\n params.turns as types.ContentListUnion,\n );\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(apiClient, item));\n } else {\n contents = contents.map((item) => contentToMldev(apiClient, item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClientRealtimeInput(\n apiClient: ApiClient,\n params: types.LiveSendRealtimeInputParameters,\n ): types.LiveClientMessage {\n let clientMessage: types.LiveClientMessage = {};\n if (!('media' in params) || !params.media) {\n throw new Error(\n `Failed to convert realtime input \"media\", type: '${typeof params.media}'`,\n );\n }\n\n // LiveClientRealtimeInput\n clientMessage = {realtimeInput: {mediaChunks: [params.media]}};\n return clientMessage;\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n if (params.media == null) {\n throw new Error('Media is required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClientRealtimeInput(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n const session = await ai.live.connect({\n model: 'gemini-2.0-flash-exp',\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_models_converters';\nimport * as types from './types';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n return await this.generateContentInternal(params);\n };\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n return await this.generateContentStreamInternal(params);\n };\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param model - The model to use.\n * @param prompt - A text description of the image to generate.\n * @param [config] - The config for image generation.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n };\n }\n return response;\n });\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n apiClient,\n chunk,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n apiClient,\n chunk,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.get({operation: operation});\n * }\n *\n * console.log(operation.result?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n async generateVideos(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function getOperationParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromMldev(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromMldev(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromVertex(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, ['response']);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromVertex(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_operations_converters';\nimport * as types from './types';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param operation The Operation object returned by a previous API call.\n * @return The updated Operation object, with the latest status or result.\n */\n async get(\n parameters: types.OperationGetParameters,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n var httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n return this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n } else {\n return this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n const body = converters.getOperationParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth';\nimport * as common from './_common';\nimport {Uploader} from './_uploader';\nimport {File, HttpOptions, HttpResponse, UploadFileConfig} from './types';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst USER_AGENT_HEADER = 'User-Agent';\nconst GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '0.7.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Client errors raised by the GenAI API.\n */\nexport class ClientError extends Error {\n constructor(message: string, stackTrace?: string) {\n if (stackTrace) {\n super(message, {cause: stackTrace});\n } else {\n super(message, {cause: new Error().stack});\n }\n this.message = message;\n this.name = 'ClientError';\n }\n}\n\n/**\n * Server errors raised by the GenAI API.\n */\nexport class ServerError extends Error {\n constructor(message: string, stackTrace?: string) {\n if (stackTrace) {\n super(message, {cause: stackTrace});\n } else {\n super(message, {cause: new Error().stack});\n }\n this.message = message;\n this.name = 'ServerError';\n }\n}\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n // Assume that proj/api key validation occurs before they are passed in.\n if (this.getProject() || this.getLocation()) {\n initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n this.clientOptions.apiKey = undefined; // unset API key.\n } else {\n initHttpOptions.baseUrl = `https://aiplatform.googleapis.com/`;\n this.clientOptions.project = undefined; // unset project.\n this.clientOptions.location = undefined; // unset location.\n }\n } else {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(path: string, httpOptions: HttpOptions): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (\n this.clientOptions.vertexai &&\n !this.clientOptions.apiKey &&\n !path.startsWith('projects/')\n ) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const url = this.constructUrl(request.path, patchedHttpOptions);\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const url = this.constructUrl(request.path, patchedHttpOptions);\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n ): Promise {\n if (httpOptions && httpOptions.timeout && httpOptions.timeout > 0) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n setTimeout(() => abortController.abort(), httpOptions.timeout);\n requestInit.signal = signal;\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value);\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const chunkData = JSON.parse(processedChunkString);\n yield chunkData;\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new ServerError('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n const statusText: string = response.statusText;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: 'exception parsing response',\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = `got status: ${status} ${statusText}. ${JSON.stringify(\n errorBody,\n )}`;\n if (status >= 400 && status < 500) {\n const clientError = new ClientError(errorMessage);\n throw clientError;\n } else if (status >= 500 && status < 600) {\n const serverError = new ServerError(errorMessage);\n throw serverError;\n }\n throw new Error(errorMessage);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuth, GoogleAuthOptions} from 'google-auth-library';\n\nimport {Auth} from '../_auth';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\nexport const AUTHORIZATION_HEADER = 'Authorization';\nconst REQUIRED_VERTEX_AI_SCOPE =\n 'https://www.googleapis.com/auth/cloud-platform';\n\nexport interface NodeAuthOptions {\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. These are the authentication options provided by google-auth-library for Vertex AI users.\n * Complete list of authentication options are documented in the\n * GoogleAuthOptions interface:\n * https://github.com/googleapis/google-auth-library-nodejs/blob/main/src/auth/googleauth.ts.\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\nexport class NodeAuth implements Auth {\n private readonly googleAuth?: GoogleAuth;\n private readonly apiKey?: string;\n\n constructor(opts: NodeAuthOptions) {\n if (opts.apiKey !== undefined) {\n this.apiKey = opts.apiKey;\n return;\n }\n const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions);\n this.googleAuth = new GoogleAuth(vertexAuthOptions);\n }\n\n async addAuthHeaders(headers: Headers): Promise {\n if (this.apiKey !== undefined) {\n this.addKeyHeader(headers);\n return;\n }\n\n return this.addGoogleAuthHeaders(headers);\n }\n\n private addKeyHeader(headers: Headers) {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n if (this.apiKey === undefined) {\n // This should never happen, this method is only called\n // when apiKey is set.\n throw new Error('Trying to set API key header but apiKey is not set');\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n\n private async addGoogleAuthHeaders(headers: Headers): Promise {\n if (headers.get(AUTHORIZATION_HEADER) !== null) {\n return;\n }\n if (this.googleAuth === undefined) {\n // This should never happen, addGoogleAuthHeaders should only be\n // called when there is no apiKey set and in these cases googleAuth\n // is set.\n throw new Error(\n 'Trying to set google-auth headers but googleAuth is unset',\n );\n }\n const token = await this.googleAuth.getAccessToken();\n headers.append(AUTHORIZATION_HEADER, `Bearer ${token}`);\n }\n}\n\nfunction buildGoogleAuthOptions(\n googleAuthOptions?: GoogleAuthOptions,\n): GoogleAuthOptions {\n let authOptions: GoogleAuthOptions;\n if (!googleAuthOptions) {\n authOptions = {\n scopes: [REQUIRED_VERTEX_AI_SCOPE],\n };\n return authOptions;\n } else {\n authOptions = googleAuthOptions;\n if (!authOptions.scopes) {\n authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE];\n return authOptions;\n } else if (\n (typeof authOptions.scopes === 'string' &&\n authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) ||\n (Array.isArray(authOptions.scopes) &&\n authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0)\n ) {\n throw new Error(\n `Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`,\n );\n }\n return authOptions;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as NodeWs from 'ws';\n\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from '../_websocket';\n\nexport class NodeWebSocketFactory implements WebSocketFactory {\n create(\n url: string,\n headers: Record,\n callbacks: WebSocketCallbacks,\n ): WebSocket {\n return new NodeWebSocket(url, headers, callbacks);\n }\n}\n\nexport class NodeWebSocket implements WebSocket {\n private ws?: NodeWs.WebSocket;\n\n constructor(\n private readonly url: string,\n private readonly headers: Record,\n private readonly callbacks: WebSocketCallbacks,\n ) {}\n\n connect(): void {\n this.ws = new NodeWs.WebSocket(this.url, {headers: this.headers});\n\n this.ws.onopen = this.callbacks.onopen;\n this.ws.onerror = this.callbacks.onerror;\n this.ws.onclose = this.callbacks.onclose;\n this.ws.onmessage = this.callbacks.onmessage;\n }\n\n send(message: string) {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.send(message);\n }\n\n close() {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.close();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client';\nimport {FileStat, Uploader} from '../_uploader';\nimport {File, HttpResponse} from '../types';\n\nimport {crossError} from './_cross_error';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.['x-goog-upload-status'] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.['x-goog-upload-status'] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as fs from 'fs/promises';\n\nimport {ApiClient} from '../_api_client';\nimport {FileStat, Uploader} from '../_uploader';\nimport {\n MAX_CHUNK_SIZE,\n getBlobStat,\n uploadBlob,\n} from '../cross/_cross_uploader';\nimport {File, HttpResponse} from '../types';\n\nexport class NodeUploader implements Uploader {\n async stat(file: string | Blob): Promise {\n const fileStat: FileStat = {size: 0, type: undefined};\n if (typeof file === 'string') {\n const originalStat = await fs.stat(file);\n fileStat.size = originalStat.size;\n fileStat.type = this.inferMimeType(file);\n return fileStat;\n } else {\n return await getBlobStat(file);\n }\n }\n\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n return await this.uploadFileFromPath(file, uploadUrl, apiClient);\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n /**\n * Infers the MIME type of a file based on its extension.\n *\n * @param filePath The path to the file.\n * @returns The MIME type of the file, or undefined if it cannot be inferred.\n */\n private inferMimeType(filePath: string): string | undefined {\n // Get the file extension.\n const fileExtension = filePath.slice(filePath.lastIndexOf('.') + 1);\n\n // Create a map of file extensions to MIME types.\n const mimeTypes: {[key: string]: string} = {\n 'aac': 'audio/aac',\n 'abw': 'application/x-abiword',\n 'arc': 'application/x-freearc',\n 'avi': 'video/x-msvideo',\n 'azw': 'application/vnd.amazon.ebook',\n 'bin': 'application/octet-stream',\n 'bmp': 'image/bmp',\n 'bz': 'application/x-bzip',\n 'bz2': 'application/x-bzip2',\n 'csh': 'application/x-csh',\n 'css': 'text/css',\n 'csv': 'text/csv',\n 'doc': 'application/msword',\n 'docx':\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'eot': 'application/vnd.ms-fontobject',\n 'epub': 'application/epub+zip',\n 'gz': 'application/gzip',\n 'gif': 'image/gif',\n 'htm': 'text/html',\n 'html': 'text/html',\n 'ico': 'image/vnd.microsoft.icon',\n 'ics': 'text/calendar',\n 'jar': 'application/java-archive',\n 'jpeg': 'image/jpeg',\n 'jpg': 'image/jpeg',\n 'js': 'text/javascript',\n 'json': 'application/json',\n 'jsonld': 'application/ld+json',\n 'kml': 'application/vnd.google-earth.kml+xml',\n 'kmz': 'application/vnd.google-earth.kmz+xml',\n 'mjs': 'text/javascript',\n 'mp3': 'audio/mpeg',\n 'mp4': 'video/mp4',\n 'mpeg': 'video/mpeg',\n 'mpkg': 'application/vnd.apple.installer+xml',\n 'odt': 'application/vnd.oasis.opendocument.text',\n 'oga': 'audio/ogg',\n 'ogv': 'video/ogg',\n 'ogx': 'application/ogg',\n 'opus': 'audio/opus',\n 'otf': 'font/otf',\n 'png': 'image/png',\n 'pdf': 'application/pdf',\n 'php': 'application/x-httpd-php',\n 'ppt': 'application/vnd.ms-powerpoint',\n 'pptx':\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'rar': 'application/vnd.rar',\n 'rtf': 'application/rtf',\n 'sh': 'application/x-sh',\n 'svg': 'image/svg+xml',\n 'swf': 'application/x-shockwave-flash',\n 'tar': 'application/x-tar',\n 'tif': 'image/tiff',\n 'tiff': 'image/tiff',\n 'ts': 'video/mp2t',\n 'ttf': 'font/ttf',\n 'txt': 'text/plain',\n 'vsd': 'application/vnd.visio',\n 'wav': 'audio/wav',\n 'weba': 'audio/webm',\n 'webm': 'video/webm',\n 'webp': 'image/webp',\n 'woff': 'font/woff',\n 'woff2': 'font/woff2',\n 'xhtml': 'application/xhtml+xml',\n 'xls': 'application/vnd.ms-excel',\n 'xlsx':\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'xml': 'application/xml',\n 'xul': 'application/vnd.mozilla.xul+xml',\n 'zip': 'application/zip',\n '3gp': 'video/3gpp',\n '3g2': 'video/3gpp2',\n '7z': 'application/x-7z-compressed',\n };\n\n // Look up the MIME type based on the file extension.\n const mimeType = mimeTypes[fileExtension.toLowerCase()];\n\n // Return the MIME type.\n return mimeType;\n }\n\n private async uploadFileFromPath(\n file: string,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n let fileHandle: fs.FileHandle | undefined;\n try {\n fileHandle = await fs.open(file, 'r');\n if (!fileHandle) {\n throw new Error(`Failed to open file`);\n }\n fileSize = (await fileHandle.stat()).size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n const buffer = new Uint8Array(chunkSize);\n const {bytesRead: bytesRead} = await fileHandle.read(\n buffer,\n 0,\n chunkSize,\n offset,\n );\n\n if (bytesRead !== chunkSize) {\n throw new Error(\n `Failed to read ${chunkSize} bytes from file at offset ${\n offset\n }. bytes actually read: ${bytesRead}`,\n );\n }\n\n const chunk = new Blob([buffer]);\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(bytesRead),\n },\n },\n });\n offset += bytesRead;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.['x-goog-upload-status'] !== 'active') {\n break;\n }\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.['x-goog-upload-status'] !== 'final') {\n throw new Error(\n 'Failed to upload file: Upload status is not finalized.',\n );\n }\n return responseJson['file'] as File;\n } finally {\n // Ensure the file handle is always closed\n if (fileHandle) {\n await fileHandle.close();\n }\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuthOptions} from 'google-auth-library';\n\nimport {ApiClient} from '../_api_client';\nimport {Caches} from '../caches';\nimport {Chats} from '../chats';\nimport {GoogleGenAIOptions} from '../client';\nimport {Files} from '../files';\nimport {Live} from '../live';\nimport {Models} from '../models';\nimport {NodeAuth} from '../node/_node_auth';\nimport {NodeWebSocketFactory} from '../node/_node_websocket';\nimport {Operations} from '../operations';\n\nimport {NodeUploader} from './_node_uploader';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link\n * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or\n * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI\n * API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API\n * services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be\n * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link\n * GoogleGenAIOptions.location} must be set, or a {@link\n * GoogleGenAIOptions.apiKey} must be set when using Express Mode.\n *\n * Explicitly passed in values in {@link GoogleGenAIOptions} will always take\n * precedence over environment variables. If both project/location and api_key\n * exist in the environment variables, the project/location will be used.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly googleAuthOptions?: GoogleAuthOptions;\n private readonly project?: string;\n private readonly location?: string;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n\n constructor(options: GoogleGenAIOptions) {\n // Validate explicitly set initializer values.\n if ((options.project || options.location) && options.apiKey) {\n throw new Error(\n 'Project/location and API key are mutually exclusive in the client initializer.',\n );\n }\n\n this.vertexai =\n options.vertexai ?? getBooleanEnv('GOOGLE_GENAI_USE_VERTEXAI') ?? false;\n const envApiKey = getEnv('GOOGLE_API_KEY');\n const envProject = getEnv('GOOGLE_CLOUD_PROJECT');\n const envLocation = getEnv('GOOGLE_CLOUD_LOCATION');\n\n this.apiKey = options.apiKey ?? envApiKey;\n this.project = options.project ?? envProject;\n this.location = options.location ?? envLocation;\n\n // Handle when to use Vertex AI in express mode (api key)\n if (options.vertexai) {\n // Explicit api_key and explicit project/location already handled above.\n if ((envProject || envLocation) && options.apiKey) {\n // Explicit api_key takes precedence over implicit project/location.\n console.debug(\n 'The user provided Vertex AI API key will take precedence over' +\n ' the project/location from the environment variables.',\n );\n this.project = undefined;\n this.location = undefined;\n } else if ((options.project || options.location) && envApiKey) {\n // Explicit project/location takes precedence over implicit api_key.\n console.debug(\n 'The user provided project/location will take precedence over' +\n ' the API key from the environment variables.',\n );\n this.apiKey = undefined;\n } else if ((envProject || envLocation) && envApiKey) {\n // Implicit project/location takes precedence over implicit api_key.\n console.debug(\n 'The project/location from the environment variables will take' +\n ' precedence over the API key from the environment variables.',\n );\n this.apiKey = undefined;\n }\n }\n\n this.apiVersion = options.apiVersion;\n const auth = new NodeAuth({\n apiKey: this.apiKey,\n googleAuthOptions: options.googleAuthOptions,\n });\n this.apiClient = new ApiClient({\n auth: auth,\n project: this.project,\n location: this.location,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version,\n uploader: new NodeUploader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory());\n this.chats = new Chats(this.models, this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n }\n}\n\nfunction getEnv(env: string): string | undefined {\n return process?.env?.[env]?.trim() ?? undefined;\n}\n\nfunction getBooleanEnv(env: string): boolean {\n return stringToBoolean(getEnv(env));\n}\n\nfunction stringToBoolean(str?: string): boolean {\n if (str === undefined) {\n return false;\n }\n return str.toLowerCase() === 'true';\n}\n"],"names":["partToMldev","common.getValueByPath","common.setValueByPath","contentToMldev","functionDeclarationToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","toolToMldev","functionCallingConfigToMldev","toolConfigToMldev","t.tContents","t.tContent","t.tCachesModel","t.tCachedContentName","partToVertex","contentToVertex","schemaToVertex","functionDeclarationToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","toolToVertex","functionCallingConfigToVertex","toolConfigToVertex","PagedItem","Outcome","Language","Type","HarmCategory","HarmBlockMethod","HarmBlockThreshold","Mode","FinishReason","HarmProbability","HarmSeverity","BlockedReason","Modality","State","DynamicRetrievalConfigMode","FunctionCallingConfigMode","MediaResolution","SafetyFilterLevel","PersonGeneration","ImagePromptLanguage","FileState","FileSource","MaskReferenceMode","ControlReferenceType","SubjectReferenceType","MediaModality","converters.createCachedContentParametersToVertex","common.formatMap","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","t.tSchema","t.tTools","t.tTool","t.tSpeechConfig","t.tModel","t.tContentsForEmbed","t.tBytes","videoFromMldev","generatedVideoFromMldev","generateVideosResponseFromMldev","generateVideosOperationFromMldev","videoFromVertex","generatedVideoFromVertex","generateVideosResponseFromVertex","generateVideosOperationFromVertex","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","types.GenerateContentResponse","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVert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IAAI,oBAAoB,EAAE,CAAC;AACtE,QAAA,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC;QACnD,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QACxC,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC;QACtC,IAAI,CAAC,UAAU,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC;;AAEnD;AAED,SAAS,MAAM,CAAC,GAAW,EAAA;;AACzB,IAAA,OAAO,MAAA,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,OAAO,KAAP,IAAA,IAAA,OAAO,uBAAP,OAAO,CAAE,GAAG,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,MAAA,GAAA,EAAA,CAAG,GAAG,CAAC,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,MAAA,GAAA,EAAA,CAAE,IAAI,EAAE,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,SAAS;AACjD;AAEA,SAAS,aAAa,CAAC,GAAW,EAAA;AAChC,IAAA,OAAO,eAAe,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACrC;AAEA,SAAS,eAAe,CAAC,GAAY,EAAA;IACnC,IAAI,GAAG,KAAK,SAAS,EAAE;AACrB,QAAA,OAAO,KAAK;AACb;AACD,IAAA,OAAO,GAAG,CAAC,WAAW,EAAE,KAAK,MAAM;AACrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@google/genai/dist/node/node.d.ts b/node_modules/@google/genai/dist/node/node.d.ts new file mode 100644 index 0000000..5132ba8 --- /dev/null +++ b/node_modules/@google/genai/dist/node/node.d.ts @@ -0,0 +1,3670 @@ +import { GoogleAuthOptions } from 'google-auth-library'; + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * 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 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, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +declare class BaseModule { +} + +/** Content blob. */ +declare interface Blob_2 { + /** Required. Raw bytes. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob } + +export declare enum BlockedReason { + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + SAFETY = "SAFETY", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT" +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: (params?: types.ListCachedContentsParameters) => Promise>; + /** + * 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 [Vertex AI 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-1.5-flash', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create(params: types.CreateCachedContentParameters): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: 'gemini-1.5-flash'}); + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * 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: 'gemini-1.5-flash'}); + * ``` + */ + delete(params: types.DeleteCachedContentParameters): Promise; + /** + * 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: 'gemini-1.5-flash', + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update(params: types.UpdateCachedContentParameters): Promise; + private listInternal; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor(apiClient: ApiClient, modelsModule: Models, model: string, config?: types.GenerateContentConfig, history?: types.Content[]); + /** + * 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); + * ``` + */ + sendMessage(params: types.SendMessageParameters): Promise; + /** + * 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); + * } + * ``` + */ + sendMessageStream(params: types.SendMessageParameters): Promise>; + /** + * 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?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, 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: types.CreateChatParameters): Chat; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +declare namespace common { + export { + formatMap, + setValueByPath, + getValueByPath, + BaseModule, + UploadFileParameters + } +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + left blank or unset. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = ContentUnion[] | ContentUnion; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** 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. + */ +export declare interface ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; +} + +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH" +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-1.5-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-1.5-pro', etc. See gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent(partOrString: PartListUnion | string): Content; + +/** + * Creates a `Part` object from a `base64` `string`. + */ +export declare function createPartFromBase64(data: string, mimeType: string): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult(outcome: Outcome, output: string): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode(code: string, language: Language): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall(name: string, args: Record): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse(id: string, name: string, response: Record): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent(partOrString: PartListUnion | string): Content; + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse { +} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse { +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +export declare enum DynamicRetrievalConfigMode { + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [FunctionDeclaration] tool and [FunctionCallingConfig] mode is set to [Mode.CODE]. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File } + +/** URI based data. */ +export declare interface FileData { + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in 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. + * Somex eamples 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 + * `common.UploadFileParameters` interface. + * @return A promise that resolves to a `types.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, + * 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); + * ``` + */ + upload(params: common.UploadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * 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); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * 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}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED" +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED" +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +export declare enum FinishReason { + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + STOP = "STOP", + MAX_TOKENS = "MAX_TOKENS", + SAFETY = "SAFETY", + RECITATION = "RECITATION", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + SPII = "SPII", + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + IMAGE_SAFETY = "IMAGE_SAFETY" +} + +declare function formatMap(templateString: string, valueMap: Record): string; + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. Required. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +export declare enum FunctionCallingConfigMode { + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + AUTO = "AUTO", + ANY = "ANY", + NONE = "NONE" +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Describes the output from the function in the OpenAPI JSON Schema + Object format. */ + response?: Schema; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; +} + +/** A function response. */ +export declare class FunctionResponse { + /** The id of the function call this response is for. Populated by the client + to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response media type of the generated candidate text. + */ + responseMimeType?: string; + /** Schema that the generated candidate text must adhere to. + */ + responseSchema?: SchemaUnion; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** Identifier for each response. + */ + responseId?: string; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * 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(): string | 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(): FunctionCall[] | undefined; + /** + * 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(): string | undefined; + /** + * 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(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. + */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. + */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. + */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. + */ + enhancedPrompt?: string; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** Whether to use the prompt rewriting logic. + */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** List of generated images. + */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. + */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 1280x720, 1920x1080 are supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation progress. */ + pubsubTopic?: string; + /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** A video generation operation. */ +export declare interface GenerateVideosOperation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The normal response of the operation in case of success. */ + response?: Record; + /** The generated videos. */ + result?: GenerateVideosResponse; +} + +/** Class that represents the parameters for generating an image. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. Optional for image to video use cases. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt is provided. */ + image?: Image_2; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: 'UNKNOWN' | 'PRIORITIZE_QUALITY' | 'BALANCED' | 'PRIORITIZE_COST'; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. e.g. 'gemini-1.5-pro-001'. */ + modelName?: string; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +declare function getValueByPath(data: unknown, keys: string[]): unknown; + +/** + * 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' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly googleAuthOptions?; + private readonly project?; + private readonly location?; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project region for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. This list must have the same size as the grounding_chunk_indices. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +export declare enum HarmBlockMethod { + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + SEVERITY = "SEVERITY", + PROBABILITY = "PROBABILITY" +} + +export declare enum HarmBlockThreshold { + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE", + OFF = "OFF" +} + +export declare enum HarmCategory { + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY" +} + +export declare enum HarmProbability { + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + NEGLIGIBLE = "NEGLIGIBLE", + LOW = "LOW", + MEDIUM = "MEDIUM", + HIGH = "HIGH" +} + +export declare enum HarmSeverity { + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH" +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE'; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. + */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image } + +export declare enum ImagePromptLanguage { + auto = "auto", + en = "en", + ja = "ja", + ko = "ko", + hi = "hi" +} + +export declare enum Language { + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + PYTHON = "PYTHON" +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental + + @remarks + If using the Gemini API, Live is currently only supported behind API + version `v1alpha`. Ensure that the API version is set to `v1alpha` when + initializing the SDK if relying on the Gemini API. + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + 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.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + onopen?: (() => void) | null; + onmessage: (e: LiveServerMessage) => void; + onerror?: ((e: ErrorEvent) => void) | null; + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `ClientContentUpdate` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `ClientContentUpdate` and the `RealtimeUpdate`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + + The following fields are supported: + - `response_logprobs` + - `response_mime_type` + - `logprobs` + - `response_schema` + - `stop_sequence` + - `routing_config` + - `audio_timestamp` + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: Content; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; +} + +/** 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. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: Content; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media: Blob_2; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; +} + +/** Response message for API call. */ +export declare interface LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; +} + +/** Sent in response to a `LiveGenerateContentSetup` message from the client. */ +export declare interface LiveServerSetupComplete { +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** 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. + */ +export declare interface MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; +} + +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC" +} + +export declare enum MediaModality { + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + TEXT = "TEXT", + IMAGE = "IMAGE", + VIDEO = "VIDEO", + AUDIO = "AUDIO", + DOCUMENT = "DOCUMENT" +} + +export declare enum MediaResolution { + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH" +} + +export declare enum Modality { + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + TEXT = "TEXT", + IMAGE = "IMAGE", + AUDIO = "AUDIO" +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +export declare enum Mode { + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI 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); + * ``` + */ + generateContent: (params: types.GenerateContentParameters) => Promise; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI 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); + * } + * ``` + */ + generateContentStream: (params: types.GenerateContentParameters) => Promise>; + /** + * Generates an image based on a text description and configuration. + * + * @param model - The model to use. + * @param prompt - A text description of the image to generate. + * @param [config] - The config for image generation. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: (params: types.GenerateImagesParameters) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * 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); + * ``` + */ + embedContent(params: types.EmbedContentParameters): Promise; + /** + * 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 ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + private generateImagesInternal; + /** + * 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); + * ``` + */ + countTokens(params: types.CountTokensParameters): Promise; + /** + * 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); + * ``` + */ + computeTokens(params: types.ComputeTokensParameters): Promise; + /** + * 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', + * 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.get({operation: operation}); + * } + * + * console.log(operation.result?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos(params: types.GenerateVideosParameters): Promise; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters { + /** The operation to be retrieved. */ + operation: GenerateVideosOperation; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param operation The Operation object returned by a previous API call. + * @return The updated Operation object, with the latest status or result. + */ + get(parameters: types.OperationGetParameters): Promise; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +export declare enum Outcome { + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + OUTCOME_OK = "OUTCOME_OK", + OUTCOME_FAILED = "OUTCOME_FAILED", + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED" +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Pagers for the GenAI List APIs. + */ +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents" +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + protected requestInternal: (params: PagedItemConfig) => Promise>; + protected idxInternal: number; + constructor(name: PagedItem, request: (params: PagedItemConfig) => Promise>, response: PagedItemResponse, params: PagedItemConfig); + private init; + private initNextPage; + /** + * 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(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * 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(): number; + /** + * 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(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * 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](): AsyncIterator; + /** + * 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(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. URI based data. */ + fileData?: FileData; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +export declare type PartUnion = Part | string; + +export declare enum PersonGeneration { + DONT_ALLOW = "DONT_ALLOW", + ALLOW_ADULT = "ALLOW_ADULT", + ALLOW_ALL = "ALLOW_ALL" +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. + */ + voiceName?: string; +} + +/** 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. + */ +export declare interface RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. + */ + categories?: string[]; + /** List of scores of each categories. + */ + scores?: number[]; + /** Internal use only. + */ + contentType?: string; +} + +export declare enum SafetyFilterLevel { + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE" +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Schema that defines the format of input and output data. + + Represents a select subset of an OpenAPI 3.0 schema object. + */ +export declare interface Schema { + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema; + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClientRealtimeInput; + private tLiveClienttToolResponse; + /** + 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: types.LiveSendClientContentParameters): void; + /** + 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: types.LiveSendRealtimeInputParameters): void; + /** + 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: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +declare function setValueByPath(data: Record, keys: string[], value: unknown): void; + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +export declare enum State { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + ACTIVE = "ACTIVE", + ERROR = "ERROR" +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** 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. + */ +export declare interface StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** 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. + */ +export declare interface SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; +} + +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT" +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional. Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. This field is only used by the Gemini Developer API services. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution { +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; +} + +export declare type ToolListUnion = Tool[]; + +export declare enum Type { + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + STRING = "STRING", + NUMBER = "NUMBER", + INTEGER = "INTEGER", + BOOLEAN = "BOOLEAN", + ARRAY = "ARRAY", + OBJECT = "OBJECT" +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + Modality, + State, + DynamicRetrievalConfigMode, + FunctionCallingConfigMode, + MediaResolution, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + FileState, + FileSource, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + MediaModality, + VideoMetadata, + CodeExecutionResult, + ExecutableCode, + FileData, + FunctionCall, + FunctionResponse, + Blob_2 as Blob, + Part, + Content, + HttpOptions, + Schema, + SafetySetting, + FunctionDeclaration, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + VertexAISearch, + VertexRagStoreRagResource, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeechConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + GoogleTypeDate, + Citation, + CitationMetadata, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + GenerateVideosConfig, + GenerateVideosParameters, + Video, + GeneratedVideo, + GenerateVideosResponse, + GenerateVideosOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + HttpResponse, + LiveCallbacks, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceConfig, + MaskReferenceImage, + ControlReferenceConfig, + ControlReferenceImage, + StyleReferenceConfig, + StyleReferenceImage, + SubjectReferenceConfig, + SubjectReferenceImage, + LiveServerSetupComplete, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + LiveServerMessage, + LiveClientSetup, + LiveClientContent, + LiveClientRealtimeInput, + LiveClientToolResponse, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendRealtimeInputParameters, + LiveSendToolResponseParameters, + OperationGetParameters, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolListUnion + } +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload(file: string | Blob, uploadUrl: string, apiClient: ApiClient): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression if the ``output_mime_type`` is + ``image/jpeg``. */ + outputCompressionQuality?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. */ + videoBytes?: string; + /** Video encoding, for example "video/mp4". */ + mimeType?: string; +} + +/** Metadata describes the input video content. */ +export declare interface VideoMetadata { + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create(url: string, headers: Record, callbacks: WebSocketCallbacks): WebSocket_2; +} + +export { } diff --git a/node_modules/@google/genai/dist/web/index.mjs b/node_modules/@google/genai/dist/web/index.mjs new file mode 100644 index 0000000..1669599 --- /dev/null +++ b/node_modules/@google/genai/dist/web/index.mjs @@ -0,0 +1,7872 @@ +/** + * @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 { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + 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 undefined; + } + 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 undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @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 (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 tPart(apiClient, 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(apiClient, 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(apiClient, item)); + } + return [tPart(apiClient, 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 _isUserPart(origin) { + if (origin === null || origin === undefined) { + return false; + } + if (_isFunctionCallPart(origin)) { + return false; + } + return true; +} +function _areUserParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + return false; + } + return origin.every(_isUserPart); +} +function tContent(apiClient, origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // @ts-expect-error: _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + if (_isUserPart(origin)) { + return { + role: 'user', + parts: tParts(apiClient, origin), + }; + } + else { + return { + role: 'model', + parts: tParts(apiClient, origin), + }; + } +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(apiClient, 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(apiClient, 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(apiClient, item)); + } + return [tContent(apiClient, origin)]; +} +function _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts) { + if (accumulatedParts.length === 0) { + return; + } + if (_areUserParts(accumulatedParts)) { + result.push({ + role: 'user', + parts: tParts(apiClient, accumulatedParts), + }); + } + else { + result.push({ + role: 'model', + parts: tParts(apiClient, accumulatedParts), + }); + } + accumulatedParts.length = 0; // clear the array inplace +} +function _handleCurrentPart(apiClient, result, accumulatedParts, currentPart) { + if (_isUserPart(currentPart) === _areUserParts(accumulatedParts)) { + accumulatedParts.push(currentPart); + } + else { + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + accumulatedParts.length = 0; + accumulatedParts.push(currentPart); + } +} +function tContents(apiClient, origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + return [tContent(apiClient, origin)]; + } + const result = []; + const accumulatedParts = []; + for (const content of origin) { + if (_isContent(content)) { + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + // @ts-expect-error: content is a Content here + result.push(content); + } + else if (typeof content === 'string' || + (typeof content === 'object' && !Array.isArray(content))) { + // @ts-expect-error: content is a part here + _handleCurrentPart(apiClient, result, accumulatedParts, content); + } + else if (Array.isArray(content)) { + // if there're consecutive user parts before the list, + // convert to UserContent and append to result + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + result.push({ + role: 'user', + parts: tParts(apiClient, content), + }); + } + else { + throw new Error(`Unsupported content type: ${typeof content}`); + } + } + _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts); + return result; +} +function processSchema(apiClient, schema) { + if (!apiClient.isVertexAI()) { + if ('default' in schema) { + throw new Error('Default value is not supported in the response schema for the Gemini API.'); + } + } + if ('anyOf' in schema) { + if (schema['anyOf'] !== undefined) { + for (const subSchema of schema['anyOf']) { + processSchema(apiClient, subSchema); + } + } + } + if ('items' in schema) { + if (schema['items'] !== undefined) { + processSchema(apiClient, schema['items']); + } + } + if ('properties' in schema) { + if (schema['properties'] !== undefined) { + for (const subSchema of Object.values(schema['properties'])) { + processSchema(apiClient, subSchema); + } + } + } +} +function tSchema(apiClient, schema) { + processSchema(apiClient, schema); + return schema; +} +function tSpeechConfig(apiClient, speechConfig) { + if (typeof speechConfig === 'object' && 'voiceConfig' in speechConfig) { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tTool(apiClient, tool) { + return tool; +} +function tTools(apiClient, tool) { + if (!Array.isArray(tool)) { + throw new Error('tool is required and must be an array of Tools'); + } + return tool; +} +/** + * 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 tBytes(apiClient, fromImageBytes) { + if (typeof fromImageBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromImageBytes; +} +function tFileName(apiClient, fromName) { + if (typeof fromName !== 'string') { + throw new Error('fromName must be a string'); + } + // Remove the files/ prefx for MLdev urls to get the actual name of the file. + if (fromName.startsWith('files/')) { + return fromName.split('files/')[1]; + } + return fromName; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function partToMldev$1(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['videoMetadata']) !== undefined) { + throw new Error('videoMetadata parameter is not supported in Gemini API.'); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$1(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['response']) !== undefined) { + throw new Error('response parameter is not supported in Gemini API.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToMldev$1() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(apiClient, 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) { + if (Array.isArray(fromContents)) { + setValueByPath(parentObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev$1(apiClient, item); + }))); + } + else { + setValueByPath(parentObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToMldev$1(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(apiClient, fromToolConfig)); + } + 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) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(apiClient, 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) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(apiClient, 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(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function functionDeclarationToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], schemaToVertex$1(apiClient, fromResponse)); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToVertex$1() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(apiClient, 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) { + if (Array.isArray(fromContents)) { + setValueByPath(parentObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex$1(apiClient, item); + }))); + } + else { + setValueByPath(parentObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$1(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToVertex$1(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(apiClient, fromToolConfig)); + } + 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) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(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) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(apiClient, 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 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) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(apiClient, 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 listCachedContentsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(apiClient, 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 fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + if (Array.isArray(fromCachedContents)) { + setValueByPath(toObject, ['cachedContents'], fromCachedContents.map((item) => { + return cachedContentFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['cachedContents'], fromCachedContents); + } + } + return toObject; +} +function cachedContentFromVertex(apiClient, 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 fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + if (Array.isArray(fromCachedContents)) { + setValueByPath(toObject, ['cachedContents'], fromCachedContents.map((item) => { + return cachedContentFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['cachedContents'], fromCachedContents); + } + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Pagers for the GenAI List APIs. + */ +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 || (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.idxInternal = 0; + let requestParams = { config: {} }; + if (!params) { + 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 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 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +var Outcome; +(function (Outcome) { + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(Outcome || (Outcome = {})); +var Language; +(function (Language) { + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +var Type; +(function (Type) { + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + Type["STRING"] = "STRING"; + Type["NUMBER"] = "NUMBER"; + Type["INTEGER"] = "INTEGER"; + Type["BOOLEAN"] = "BOOLEAN"; + Type["ARRAY"] = "ARRAY"; + Type["OBJECT"] = "OBJECT"; +})(Type || (Type = {})); +var HarmCategory; +(function (HarmCategory) { + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; +})(HarmCategory || (HarmCategory = {})); +var HarmBlockMethod; +(function (HarmBlockMethod) { + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +var Mode; +(function (Mode) { + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(Mode || (Mode = {})); +var FinishReason; +(function (FinishReason) { + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + FinishReason["STOP"] = "STOP"; + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + FinishReason["SAFETY"] = "SAFETY"; + FinishReason["RECITATION"] = "RECITATION"; + FinishReason["OTHER"] = "OTHER"; + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + FinishReason["SPII"] = "SPII"; + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(FinishReason || (FinishReason = {})); +var HarmProbability; +(function (HarmProbability) { + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + HarmProbability["LOW"] = "LOW"; + HarmProbability["MEDIUM"] = "MEDIUM"; + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +var HarmSeverity; +(function (HarmSeverity) { + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +var BlockedReason; +(function (BlockedReason) { + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + BlockedReason["SAFETY"] = "SAFETY"; + BlockedReason["OTHER"] = "OTHER"; + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; +})(BlockedReason || (BlockedReason = {})); +var Modality; +(function (Modality) { + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + Modality["TEXT"] = "TEXT"; + Modality["IMAGE"] = "IMAGE"; + Modality["AUDIO"] = "AUDIO"; +})(Modality || (Modality = {})); +var State; +(function (State) { + State["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + State["ACTIVE"] = "ACTIVE"; + State["ERROR"] = "ERROR"; +})(State || (State = {})); +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + FunctionCallingConfigMode["AUTO"] = "AUTO"; + FunctionCallingConfigMode["ANY"] = "ANY"; + FunctionCallingConfigMode["NONE"] = "NONE"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +var MediaResolution; +(function (MediaResolution) { + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +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 = {})); +var PersonGeneration; +(function (PersonGeneration) { + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + ImagePromptLanguage["auto"] = "auto"; + ImagePromptLanguage["en"] = "en"; + ImagePromptLanguage["ja"] = "ja"; + ImagePromptLanguage["ko"] = "ko"; + ImagePromptLanguage["hi"] = "hi"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(FileSource || (FileSource = {})); +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 = {})); +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 = {})); +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 = {})); +var MediaModality; +(function (MediaModality) { + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + MediaModality["TEXT"] = "TEXT"; + MediaModality["IMAGE"] = "IMAGE"; + MediaModality["VIDEO"] = "VIDEO"; + MediaModality["AUDIO"] = "AUDIO"; + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * 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) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * 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), + }; +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +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' && + (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 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 counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** 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(); + } +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** 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 = []; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for (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 [Vertex AI 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-1.5-flash', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + 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: 'gemini-1.5-flash'}); + * ``` + */ + async get(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + 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: 'gemini-1.5-flash'}); + * ``` + */ + async delete(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + 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: 'gemini-1.5-flash', + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(this.apiClient, apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(this.apiClient, 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 __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; + } + if (part.text !== undefined && part.text === '') { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @remarks + * Expects the history to start with a user turn and then alternate between + * user and model turns. + * + * @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; + } + if (history[0].role !== 'user') { + throw new Error('History must start with a user turn.'); + } + 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; + let userInput = comprehensiveHistory[0]; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + userInput = 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(userInput); + curatedHistory.push(...modelOutput); + } + } + } + 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, 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(this.apiClient, 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; + 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; + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput); + return; + })(); + await this.sendPromise; + 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(this.apiClient, 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, + }); + this.sendPromise = streamResponse.then(() => 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) { + return curated ? extractCuratedHistory(this.history) : this.history; + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.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 && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role === 'model')) { + 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: [], + }); + } + this.history.push(userInput); + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function listFilesConfigToMldev(apiClient, 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(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(apiClient, fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(apiClient, 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 fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(apiClient, fromError)); + } + return toObject; +} +function createFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(apiClient, fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(apiClient, 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 fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(apiClient, fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + if (Array.isArray(fromFiles)) { + setValueByPath(toObject, ['files'], fromFiles.map((item) => { + return fileFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['files'], fromFiles); + } + } + return toObject; +} +function createFileResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromHttpHeaders = getValueByPath(fromObject, ['httpHeaders']); + if (fromHttpHeaders != null) { + setValueByPath(toObject, ['httpHeaders'], fromHttpHeaders); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + 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 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. + * Somex eamples 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 + * `common.UploadFileParameters` interface. + * @return A promise that resolves to a `types.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, + * 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('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(this.apiClient, response); + return file; + }); + } + async listInternal(params) { + var _a; + 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(this.apiClient, params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a; + 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(this.apiClient, params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(this.apiClient, 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; + 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(this.apiClient, params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(this.apiClient, apiResponse); + 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; + 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(this.apiClient, params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function partToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['videoMetadata']) !== undefined) { + throw new Error('videoMetadata parameter is not supported in Gemini API.'); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToMldev(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['example']) !== undefined) { + throw new Error('example parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['pattern']) !== undefined) { + throw new Error('pattern parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['default']) !== undefined) { + throw new Error('default parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['maxLength']) !== undefined) { + throw new Error('maxLength parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['minLength']) !== undefined) { + throw new Error('minLength parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['minProperties']) !== undefined) { + throw new Error('minProperties parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['maxProperties']) !== undefined) { + throw new Error('maxProperties parameter is not supported in Gemini API.'); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['response']) !== undefined) { + throw new Error('response parameter is not supported in Gemini API.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToMldev() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(apiClient, fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(apiClient, fromVoiceConfig)); + } + return toObject; +} +function thinkingConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev(apiClient, tContent(apiClient, 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'], schemaToMldev(apiClient, tSchema(apiClient, fromResponseSchema))); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + if (Array.isArray(fromSafetySettings)) { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings.map((item) => { + return safetySettingToMldev(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings); + } + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], tTools(apiClient, tTools(apiClient, fromTools).map((item) => { + return toolToMldev(apiClient, tTool(apiClient, item)); + }))); + } + else { + setValueByPath(parentObject, ['tools'], tTools(apiClient, fromTools)); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(apiClient, fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + 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'], speechConfigToMldev(apiClient, tSpeechConfig(apiClient, fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(apiClient, fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(apiClient, 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 not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(apiClient, fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + 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); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + 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); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function countTokensConfigToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToMldev(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(apiClient, fromConfig)); + } + return toObject; +} +function imageToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(apiClient, fromObject, parentObject) { + 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 not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + 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 not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + if (getValueByPath(fromObject, ['resolution']) !== undefined) { + throw new Error('resolution parameter is not supported in Gemini API.'); + } + 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 not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + 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(apiClient, fromImage)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentToVertex(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partToVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(apiClient, fromObject) { + const toObject = {}; + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(apiClient, fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], schemaToVertex(apiClient, fromResponse)); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + return toObject; +} +function googleSearchToVertex() { + const toObject = {}; + return toObject; +} +function dynamicRetrievalConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig)); + } + return toObject; +} +function toolToVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + if (Array.isArray(fromFunctionDeclarations)) { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations.map((item) => { + return functionDeclarationToVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['functionDeclarations'], fromFunctionDeclarations); + } + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex()); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function toolConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(apiClient, fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(apiClient, fromVoiceConfig)); + } + return toObject; +} +function thinkingConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(apiClient, tContent(apiClient, 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'], schemaToVertex(apiClient, tSchema(apiClient, fromResponseSchema))); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + if (Array.isArray(fromSafetySettings)) { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings.map((item) => { + return safetySettingToVertex(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['safetySettings'], fromSafetySettings); + } + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], tTools(apiClient, tTools(apiClient, fromTools).map((item) => { + return toolToVertex(apiClient, tTool(apiClient, item)); + }))); + } + else { + setValueByPath(parentObject, ['tools'], tTools(apiClient, fromTools)); + } + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(apiClient, 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(apiClient, tSpeechConfig(apiClient, fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(apiClient, fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(apiClient, fromObject, parentObject) { + 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 fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + 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) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function countTokensConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(apiClient, tContent(apiClient, fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + if (Array.isArray(fromTools)) { + setValueByPath(parentObject, ['tools'], fromTools.map((item) => { + return toolToVertex(apiClient, item); + })); + } + else { + setValueByPath(parentObject, ['tools'], fromTools); + } + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + 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) { + if (Array.isArray(fromContents)) { + setValueByPath(toObject, ['contents'], tContents(apiClient, tContents(apiClient, fromContents).map((item) => { + return contentToVertex(apiClient, item); + }))); + } + else { + setValueByPath(toObject, ['contents'], tContents(apiClient, fromContents)); + } + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function imageToVertex(apiClient, fromObject) { + 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(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToVertex(apiClient, fromObject, parentObject) { + 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); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + 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(apiClient, fromImage)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function partFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function candidateFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(apiClient, fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(apiClient, 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 fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + 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) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + if (Array.isArray(fromCandidates)) { + setValueByPath(toObject, ['candidates'], fromCandidates.map((item) => { + return candidateFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['candidates'], fromCandidates); + } + } + 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 fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + if (Array.isArray(fromEmbeddings)) { + setValueByPath(toObject, ['embeddings'], fromEmbeddings.map((item) => { + return contentEmbeddingFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['embeddings'], fromEmbeddings); + } + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(apiClient, fromObject) { + 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 generatedImageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(apiClient, fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(apiClient, fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + if (Array.isArray(fromGeneratedImages)) { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages.map((item) => { + return generatedImageFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages); + } + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(apiClient, fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function countTokensResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + 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 videoFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev$1(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev$1(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromMldev$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromMldev$1(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromMldev$1(apiClient, fromResult)); + } + return toObject; +} +function partFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + 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); + } + return toObject; +} +function contentFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + if (Array.isArray(fromParts)) { + setValueByPath(toObject, ['parts'], fromParts.map((item) => { + return partFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['parts'], fromParts); + } + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function candidateFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(apiClient, fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(apiClient, fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + 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) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + if (Array.isArray(fromCandidates)) { + setValueByPath(toObject, ['candidates'], fromCandidates.map((item) => { + return candidateFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['candidates'], fromCandidates); + } + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + 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 fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(apiClient, fromObject) { + 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); + } + return toObject; +} +function contentEmbeddingFromVertex(apiClient, fromObject) { + 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(apiClient, fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + if (Array.isArray(fromEmbeddings)) { + setValueByPath(toObject, ['embeddings'], fromEmbeddings.map((item) => { + return contentEmbeddingFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['embeddings'], fromEmbeddings); + } + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(apiClient, fromMetadata)); + } + return toObject; +} +function imageFromVertex(apiClient, fromObject) { + 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(apiClient, fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(apiClient, fromObject) { + 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 generatedImageFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(apiClient, 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(apiClient, fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + if (Array.isArray(fromGeneratedImages)) { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages.map((item) => { + return generatedImageFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedImages'], fromGeneratedImages); + } + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(apiClient, fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function countTokensResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex$1(apiClient, 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(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex$1(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex$1(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromVertex$1(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromVertex$1(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, ['response']); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromVertex$1(apiClient, fromResult)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Converters for live client. + */ +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig !== undefined && fromConfig !== null) { + setValueByPath(toObject, ['setup'], liveConnectConfigToMldev(apiClient, fromConfig)); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel !== undefined) { + setValueByPath(toObject, ['setup', 'model'], fromModel); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig !== undefined && fromConfig !== null) { + setValueByPath(toObject, ['setup'], liveConnectConfigToVertex(apiClient, fromConfig)); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel !== undefined) { + setValueByPath(toObject, ['setup', 'model'], fromModel); + } + return toObject; +} +function liveServerMessageFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete !== undefined) { + setValueByPath(toObject, ['setupComplete'], fromSetupComplete); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent !== undefined && fromServerContent !== null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(apiClient, fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall !== undefined && fromToolCall !== null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(apiClient, fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation !== undefined && + fromToolCallCancellation !== null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(apiClient, fromToolCallCancellation)); + } + return toObject; +} +function liveServerMessageFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete !== undefined) { + setValueByPath(toObject, ['setupComplete'], fromSetupComplete); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent !== undefined && fromServerContent !== null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(apiClient, fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall !== undefined && fromToolCall !== null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(apiClient, fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation !== undefined && + fromToolCallCancellation !== null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(apiClient, fromToolCallCancellation)); + } + return toObject; +} +function liveConnectConfigToMldev(apiClient, fromObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (fromGenerationConfig !== undefined) { + setValueByPath(toObject, ['generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities !== undefined) { + setValueByPath(toObject, ['generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig !== undefined) { + setValueByPath(toObject, ['generationConfig', 'speechConfig'], fromSpeechConfig); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) { + setValueByPath(toObject, ['systemInstruction'], contentToMldev(apiClient, fromSystemInstruction)); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (fromTools !== undefined && + fromTools !== null && + Array.isArray(fromTools)) { + setValueByPath(toObject, ['tools'], fromTools.map((item) => { + return toolToMldev(apiClient, item); + })); + } + return toObject; +} +function liveConnectConfigToVertex(apiClient, fromObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (fromGenerationConfig !== undefined) { + setValueByPath(toObject, ['generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities !== undefined) { + setValueByPath(toObject, ['generationConfig', 'responseModalities'], fromResponseModalities); + } + else { + // Set default to AUDIO to align with MLDev API. + setValueByPath(toObject, ['generationConfig', 'responseModalities'], ['AUDIO']); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig !== undefined) { + setValueByPath(toObject, ['generationConfig', 'speechConfig'], fromSpeechConfig); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) { + setValueByPath(toObject, ['systemInstruction'], contentToVertex(apiClient, fromSystemInstruction)); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (fromTools !== undefined && + fromTools !== null && + Array.isArray(fromTools)) { + setValueByPath(toObject, ['tools'], fromTools.map((item) => { + return toolToVertex(apiClient, item); + })); + } + return toObject; +} +function liveServerContentFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn !== undefined && fromModelTurn !== null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev(apiClient, fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete !== undefined) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted !== undefined) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + return toObject; +} +function liveServerContentFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn !== undefined && fromModelTurn !== null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex(apiClient, fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete !== undefined) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted !== undefined) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + return toObject; +} +function functionCallFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId !== undefined) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs !== undefined) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName !== undefined) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function functionCallFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs !== undefined) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName !== undefined) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls !== undefined && + fromFunctionCalls !== null && + Array.isArray(fromFunctionCalls)) { + setValueByPath(toObject, ['functionCalls'], fromFunctionCalls.map((item) => { + return functionCallFromMldev(apiClient, item); + })); + } + return toObject; +} +function liveServerToolCallFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls !== undefined && + fromFunctionCalls !== null && + Array.isArray(fromFunctionCalls)) { + setValueByPath(toObject, ['functionCalls'], fromFunctionCalls.map((item) => { + return functionCallFromVertex(apiClient, item); + })); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds !== undefined) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds !== undefined) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} + +/** + * @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) { + let serverMessage; + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + if (apiClient.isVertexAI()) { + serverMessage = liveServerMessageFromVertex(apiClient, data); + } + else { + serverMessage = liveServerMessageFromMldev(apiClient, data); + } + 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; + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental + + @remarks + If using the Gemini API, Live is currently only supported behind API + version `v1alpha`. Ensure that the API version is set to `v1alpha` when + initializing the SDK if relying on the Gemini API. + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + 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; + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const headers = mapToHeaders(this.apiClient.getDefaultHeaders()); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateContent?key=${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; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(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(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(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + 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); + } + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } +} +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(apiClient, params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(apiClient, item)); + } + else { + contents = contents.map((item) => contentToMldev(apiClient, 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 }, + }; + } + tLiveClientRealtimeInput(apiClient, params) { + let clientMessage = {}; + if (!('media' in params) || !params.media) { + throw new Error(`Failed to convert realtime input "media", type: '${typeof params.media}'`); + } + // LiveClientRealtimeInput + clientMessage = { realtimeInput: { mediaChunks: [params.media] } }; + return clientMessage; + } + 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) { + if (params.media == null) { + throw new Error('Media is required.'); + } + const clientMessage = this.tLiveClientRealtimeInput(this.apiClient, 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 + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + 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 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI 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) => { + return await this.generateContentInternal(params); + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI 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) => { + return await this.generateContentStreamInternal(params); + }; + /** + * Generates an image based on a text description and configuration. + * + * @param model - The model to use. + * @param prompt - A text description of the image to generate. + * @param [config] - The config for image generation. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + 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, + }; + } + else { + response = { + generatedImages: generatedImages, + }; + } + return response; + }); + }; + } + async generateContentInternal(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(this.apiClient, 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b; + 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['config']; + 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, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_1, _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(apiClient, chunk); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _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(apiClient, chunk); + 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_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_2) throw e_2.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 embedContent(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * 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 ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(this.apiClient, apiResponse); + const typedResp = new GenerateImagesResponse(); + 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; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(this.apiClient, 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['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(this.apiClient, 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; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(this.apiClient, apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * 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', + * 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.get({operation: operation}); + * } + * + * console.log(operation.result?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideos(params) { + var _a, _b; + 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['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex$1(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev$1(this.apiClient, apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function getOperationParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(apiClient, 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); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromMldev(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromMldev(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromMldev(apiClient, fromResult)); + } + return toObject; +} +function videoFromVertex(apiClient, 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(apiClient, fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(apiClient, fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(apiClient, fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + if (Array.isArray(fromGeneratedVideos)) { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos.map((item) => { + return generatedVideoFromVertex(apiClient, item); + })); + } + else { + setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos); + } + } + 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 generateVideosOperationFromVertex(apiClient, 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'], fromResponse); + } + const fromResult = getValueByPath(fromObject, ['response']); + if (fromResult != null) { + setValueByPath(toObject, ['result'], generateVideosResponseFromVertex(apiClient, fromResult)); + } + return toObject; +} + +/** + * @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 operation The Operation object returned by a previous API call. + * @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]; + var httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + return this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + } + else { + return this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(this.apiClient, params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + const body = getOperationParametersToMldev(this.apiClient, params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_b = params.config) === null || _b === void 0 ? void 0 : _b.httpOptions, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(this.apiClient, apiResponse); + return resp; + }); + } + } + async fetchPredictVideosOperationInternal(params) { + var _a; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(this.apiClient, params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + 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, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(this.apiClient, apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '0.7.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 responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * Client errors raised by the GenAI API. + */ +class ClientError extends Error { + constructor(message, stackTrace) { + if (stackTrace) { + super(message, { cause: stackTrace }); + } + else { + super(message, { cause: new Error().stack }); + } + this.message = message; + this.name = 'ClientError'; + } +} +/** + * Server errors raised by the GenAI API. + */ +class ServerError extends Error { + constructor(message, stackTrace) { + if (stackTrace) { + super(message, { cause: stackTrace }); + } + else { + super(message, { cause: new Error().stack }); + } + this.message = message; + this.name = 'ServerError'; + } +} +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + // Assume that proj/api key validation occurs before they are passed in. + if (this.getProject() || this.getLocation()) { + initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + this.clientOptions.apiKey = undefined; // unset API key. + } + else { + initHttpOptions.baseUrl = `https://aiplatform.googleapis.com/`; + this.clientOptions.project = undefined; // unset project. + this.clientOptions.location = undefined; // unset location. + } + } + else { + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : 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; + } + 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 = '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) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (this.clientOptions.vertexai && + !this.clientOptions.apiKey && + !path.startsWith('projects/')) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const url = this.constructUrl(request.path, patchedHttpOptions); + 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); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + 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 url = this.constructUrl(request.path, patchedHttpOptions); + 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); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions) { + if (httpOptions && httpOptions.timeout && httpOptions.timeout > 0) { + const abortController = new AbortController(); + const signal = abortController.signal; + setTimeout(() => abortController.abort(), httpOptions.timeout); + requestInit.signal = signal; + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + 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 = ''; + 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); + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const chunkData = JSON.parse(processedChunkString); + yield yield __await(chunkData); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + 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) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * 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 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 uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + 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 ServerError('response is undefined'); + } + if (!response.ok) { + const status = response.status; + const statusText = response.statusText; + 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: 'exception parsing response', + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = `got status: ${status} ${statusText}. ${JSON.stringify(errorBody)}`; + if (status >= 400 && status < 500) { + const clientError = new ClientError(errorMessage); + throw clientError; + } + else if (status >= 500 && status < 600) { + const serverError = new ServerError(errorMessage); + throw serverError; + } + throw new Error(errorMessage); + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b; + 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'; + } + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-status']) !== '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.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b['x-goog-upload-status']) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} + +class BrowserUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + throw new Error('File path is not supported in browser uploader.'); + } + return await uploadBlob(file, uploadUrl, apiClient); + } + async stat(file) { + if (typeof file === 'string') { + throw new Error('File path is not supported in browser uploader.'); + } + else { + return await getBlobStat(file); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO((b/401271082): re-enable lint once BrowserWebSocketFactory is +// implemented. +/* eslint-disable @typescript-eslint/no-unused-vars */ +class BrowserWebSocketFactory { + create(url, headers, callbacks) { + return new BrowserWebSocket(url, headers, callbacks); + } +} +class BrowserWebSocket { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new WebSocket(this.url); + 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 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * 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, currently only {@link GoogleGenAIOptions.apiKey} + * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} should not be set. + * + * @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 { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error('An API Key must be set when running in a browser'); + } + // Web client only supports API key mode for Vertex AI. + if (options.project || options.location) { + throw new Error('Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.'); + } + this.vertexai = (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + 'web', + uploader: new BrowserUploader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory()); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + } +} + +export { BlockedReason, Caches, Chat, Chats, ComputeTokensResponse, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DynamicRetrievalConfigMode, EmbedContentResponse, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpResponse, ImagePromptLanguage, Language, ListCachedContentsResponse, ListFilesResponse, Live, LiveClientToolResponse, LiveSendToolResponseParameters, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, Operations, Outcome, PagedItem, Pager, PersonGeneration, ReplayResponse, SafetyFilterLevel, Session, State, SubjectReferenceType, Type, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent }; +//# sourceMappingURL=index.mjs.map diff --git a/node_modules/@google/genai/dist/web/index.mjs.map b/node_modules/@google/genai/dist/web/index.mjs.map new file mode 100644 index 0000000..b85758c --- /dev/null +++ b/node_modules/@google/genai/dist/web/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../../src/_common.ts","../../src/_transformers.ts","../../src/converters/_caches_converters.ts","../../src/pagers.ts","../../src/types.ts","../../src/caches.ts","../../src/chats.ts","../../src/converters/_files_converters.ts","../../src/files.ts","../../src/converters/_models_converters.ts","../../src/converters/_live_converters.ts","../../src/live.ts","../../src/models.ts","../../src/converters/_operations_converters.ts","../../src/operations.ts","../../src/_api_client.ts","../../src/cross/_cross_uploader.ts","../../src/web/_browser_uploader.ts","../../src/web/_browser_websocket.ts","../../src/web/_web_auth.ts","../../src/web/web_client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {UploadFileConfig} from './types';\n\nexport class BaseModule {}\n\n// TODO (b/406332263): Move this to a place where it can be linked for doc.\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client';\nimport * as types from './types';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tPart(\n apiClient: ApiClient,\n origin?: types.PartUnion | null,\n): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(\n apiClient: ApiClient,\n origin?: types.PartListUnion | null,\n): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(apiClient, item as types.PartUnion)!);\n }\n return [tPart(apiClient, origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isUserPart(origin: unknown): boolean {\n if (origin === null || origin === undefined) {\n return false;\n }\n if (_isFunctionCallPart(origin)) {\n return false;\n }\n return true;\n}\n\nfunction _areUserParts(origin: types.PartListUnion[]): boolean {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n return false;\n }\n return origin.every(_isUserPart);\n}\n\nexport function tContent(\n apiClient: ApiClient,\n origin?: types.ContentUnion,\n): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // @ts-expect-error: _isContent is a utility function that checks if the\n // origin is a Content.\n return origin;\n }\n\n if (_isUserPart(origin)) {\n return {\n role: 'user',\n parts: tParts(apiClient, origin as types.PartListUnion)!,\n };\n } else {\n return {\n role: 'model',\n parts: tParts(apiClient, origin as types.PartListUnion)!,\n };\n }\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(apiClient, item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(apiClient, origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map(\n (item) => tContent(apiClient, item as types.ContentUnion)!,\n );\n }\n return [tContent(apiClient, origin as types.ContentUnion)!];\n}\n\nfunction _appendAccumulatedPartsAsContent(\n apiClient: ApiClient,\n result: types.Content[],\n accumulatedParts: types.PartUnion[],\n) {\n if (accumulatedParts.length === 0) {\n return;\n }\n if (_areUserParts(accumulatedParts)) {\n result.push({\n role: 'user',\n parts: tParts(apiClient, accumulatedParts),\n });\n } else {\n result.push({\n role: 'model',\n parts: tParts(apiClient, accumulatedParts),\n });\n }\n accumulatedParts.length = 0; // clear the array inplace\n}\n\nfunction _handleCurrentPart(\n apiClient: ApiClient,\n result: types.Content[],\n accumulatedParts: types.PartUnion[],\n currentPart: types.PartUnion,\n) {\n if (_isUserPart(currentPart) === _areUserParts(accumulatedParts)) {\n accumulatedParts.push(currentPart);\n } else {\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n accumulatedParts.length = 0;\n accumulatedParts.push(currentPart);\n }\n}\n\nexport function tContents(\n apiClient: ApiClient,\n origin?: types.ContentListUnion,\n): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n return [tContent(apiClient, origin)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n\n for (const content of origin) {\n if (_isContent(content)) {\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n // @ts-expect-error: content is a Content here\n result.push(content);\n } else if (\n typeof content === 'string' ||\n (typeof content === 'object' && !Array.isArray(content))\n ) {\n // @ts-expect-error: content is a part here\n _handleCurrentPart(apiClient, result, accumulatedParts, content);\n } else if (Array.isArray(content)) {\n // if there're consecutive user parts before the list,\n // convert to UserContent and append to result\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n result.push({\n role: 'user',\n parts: tParts(apiClient, content),\n });\n } else {\n throw new Error(`Unsupported content type: ${typeof content}`);\n }\n }\n _appendAccumulatedPartsAsContent(apiClient, result, accumulatedParts);\n\n return result;\n}\n\nexport function processSchema(apiClient: ApiClient, schema: types.Schema) {\n if (!apiClient.isVertexAI()) {\n if ('default' in schema) {\n throw new Error(\n 'Default value is not supported in the response schema for the Gemini API.',\n );\n }\n }\n\n if ('anyOf' in schema) {\n if (schema['anyOf'] !== undefined) {\n for (const subSchema of schema['anyOf']) {\n processSchema(apiClient, subSchema);\n }\n }\n }\n\n if ('items' in schema) {\n if (schema['items'] !== undefined) {\n processSchema(apiClient, schema['items']);\n }\n }\n\n if ('properties' in schema) {\n if (schema['properties'] !== undefined) {\n for (const subSchema of Object.values(schema['properties'])) {\n processSchema(apiClient, subSchema);\n }\n }\n }\n}\n\nexport function tSchema(\n apiClient: ApiClient,\n schema: types.Schema,\n): types.Schema {\n processSchema(apiClient, schema);\n return schema;\n}\n\nexport function tSpeechConfig(\n apiClient: ApiClient,\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object' && 'voiceConfig' in speechConfig) {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tTool(apiClient: ApiClient, tool: types.Tool): types.Tool {\n return tool;\n}\n\nexport function tTools(\n apiClient: ApiClient,\n tool: types.Tool[] | unknown,\n): types.Tool[] {\n if (!Array.isArray(tool)) {\n throw new Error('tool is required and must be an array of Tools');\n }\n return tool;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(\n apiClient: ApiClient,\n status: string | unknown,\n): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(\n apiClient: ApiClient,\n fromImageBytes: string | unknown,\n): string {\n if (typeof fromImageBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromImageBytes;\n}\nexport function tFileName(\n apiClient: ApiClient,\n fromName: string | unknown,\n): string {\n if (typeof fromName !== 'string') {\n throw new Error('fromName must be a string');\n }\n // Remove the files/ prefx for MLdev urls to get the actual name of the file.\n if (fromName.startsWith('files/')) {\n return fromName.split('files/')[1];\n }\n return fromName;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function partToMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['videoMetadata']) !== undefined) {\n throw new Error('videoMetadata parameter is not supported in Gemini API.');\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['example']) !== undefined) {\n throw new Error('example parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['pattern']) !== undefined) {\n throw new Error('pattern parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['default']) !== undefined) {\n throw new Error('default parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxLength']) !== undefined) {\n throw new Error('maxLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minLength']) !== undefined) {\n throw new Error('minLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minProperties']) !== undefined) {\n throw new Error('minProperties parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxProperties']) !== undefined) {\n throw new Error('maxProperties parameter is not supported in Gemini API.');\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['response']) !== undefined) {\n throw new Error('response parameter is not supported in Gemini API.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToMldev(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToMldev());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(apiClient, fromToolConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partToVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n schemaToVertex(apiClient, fromResponse),\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToVertex(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToVertex());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(apiClient, fromToolConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n apiClient: ApiClient,\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n if (Array.isArray(fromCachedContents)) {\n common.setValueByPath(\n toObject,\n ['cachedContents'],\n fromCachedContents.map((item) => {\n return cachedContentFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['cachedContents'], fromCachedContents);\n }\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n apiClient: ApiClient,\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n if (Array.isArray(fromCachedContents)) {\n common.setValueByPath(\n toObject,\n ['cachedContents'],\n fromCachedContents.map((item) => {\n return cachedContentFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['cachedContents'], fromCachedContents);\n }\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nexport enum Outcome {\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n OUTCOME_OK = 'OUTCOME_OK',\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\nexport enum Language {\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n PYTHON = 'PYTHON',\n}\n\nexport enum Type {\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n STRING = 'STRING',\n NUMBER = 'NUMBER',\n INTEGER = 'INTEGER',\n BOOLEAN = 'BOOLEAN',\n ARRAY = 'ARRAY',\n OBJECT = 'OBJECT',\n}\n\nexport enum HarmCategory {\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n}\n\nexport enum HarmBlockMethod {\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n SEVERITY = 'SEVERITY',\n PROBABILITY = 'PROBABILITY',\n}\n\nexport enum HarmBlockThreshold {\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n OFF = 'OFF',\n}\n\nexport enum Mode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\nexport enum FinishReason {\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n STOP = 'STOP',\n MAX_TOKENS = 'MAX_TOKENS',\n SAFETY = 'SAFETY',\n RECITATION = 'RECITATION',\n OTHER = 'OTHER',\n BLOCKLIST = 'BLOCKLIST',\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n SPII = 'SPII',\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\nexport enum HarmProbability {\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n NEGLIGIBLE = 'NEGLIGIBLE',\n LOW = 'LOW',\n MEDIUM = 'MEDIUM',\n HIGH = 'HIGH',\n}\n\nexport enum HarmSeverity {\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\nexport enum BlockedReason {\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n SAFETY = 'SAFETY',\n OTHER = 'OTHER',\n BLOCKLIST = 'BLOCKLIST',\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n}\n\nexport enum Modality {\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n TEXT = 'TEXT',\n IMAGE = 'IMAGE',\n AUDIO = 'AUDIO',\n}\n\nexport enum State {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n ACTIVE = 'ACTIVE',\n ERROR = 'ERROR',\n}\n\nexport enum DynamicRetrievalConfigMode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\nexport enum FunctionCallingConfigMode {\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n AUTO = 'AUTO',\n ANY = 'ANY',\n NONE = 'NONE',\n}\n\nexport enum MediaResolution {\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\nexport enum PersonGeneration {\n DONT_ALLOW = 'DONT_ALLOW',\n ALLOW_ADULT = 'ALLOW_ADULT',\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\nexport enum ImagePromptLanguage {\n auto = 'auto',\n en = 'en',\n ja = 'ja',\n ko = 'ko',\n hi = 'hi',\n}\n\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\nexport enum MediaModality {\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n TEXT = 'TEXT',\n IMAGE = 'IMAGE',\n VIDEO = 'VIDEO',\n AUDIO = 'AUDIO',\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Metadata describes the input video content. */\nexport declare interface VideoMetadata {\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [FunctionDeclaration] tool and [FunctionCallingConfig] mode is set to [Mode.CODE]. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. Required. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** The id of the function call this response is for. Populated by the client\n to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Required. Raw bytes. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n left blank or unset. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n}\n\n/** Schema that defines the format of input and output data.\n\n Represents a select subset of an OpenAPI 3.0 schema object.\n */\nexport declare interface Schema {\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Describes the output from the function in the OpenAPI JSON Schema\n Object format. */\n response?: Schema;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. This field is only used by the Gemini Developer API services. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use.\n */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. e.g. 'gemini-1.5-pro-001'. */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response media type of the generated candidate text.\n */\n responseMimeType?: string;\n /** Schema that the generated candidate text must adhere to.\n */\n responseSchema?: SchemaUnion;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. This list must have the same size as the grounding_chunk_indices. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** Identifier for each response.\n */\n responseId?: string;\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `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.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport /** Optional parameters for the embed_content method. */\ndeclare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images.\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** Whether to use the prompt rewriting logic.\n */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both.\n */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories.\n */\n categories?: string[];\n /** List of scores of each categories.\n */\n scores?: number[];\n /** Internal use only.\n */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data.\n */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response.\n */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content.\n */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled.\n */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** List of generated images.\n */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True.\n */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional. Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 1280x720, 1920x1080 are supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation progress. */\n pubsubTopic?: string;\n /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** Class that represents the parameters for generating an image. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos. Optional for image to video use cases. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt is provided. */\n image?: Image;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes. */\n videoBytes?: string;\n /** Video encoding, for example \"video/mp4\". */\n mimeType?: string;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** A video generation operation. */\nexport declare interface GenerateVideosOperation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The normal response of the operation in case of success. */\n response?: Record;\n /** The generated videos. */\n result?: GenerateVideosResponse;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-1.5-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n onopen?: (() => void) | null;\n onmessage: (e: LiveServerMessage) => void;\n onerror?: ((e: ErrorEvent) => void) | null;\n onclose?: ((e: CloseEvent) => void) | null;\n}\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression if the ``output_mime_type`` is\n ``image/jpeg``. */\n outputCompressionQuality?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport declare interface RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport declare interface MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport declare interface ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport declare interface StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport declare interface SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n}\n\n/** Sent in response to a `LiveGenerateContentSetup` message from the client. */\nexport declare interface LiveServerSetupComplete {}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Response message for API call. */\nexport declare interface LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n\nThe following fields are supported:\n- `response_logprobs`\n- `response_mime_type`\n- `logprobs`\n- `response_schema`\n- `stop_sequence`\n- `routing_config`\n- `audio_timestamp`\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: Content;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** User input that is sent in real time.\n\n This is different from `ClientContentUpdate` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `ClientContentUpdate` and the `RealtimeUpdate`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: Content;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-1.5-pro', etc. See gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media: Blob;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters {\n /** The operation to be retrieved. */\n operation: GenerateVideosOperation;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = ContentUnion[] | ContentUnion;\n\nexport type SchemaUnion = Schema;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolListUnion = Tool[];\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_caches_converters';\nimport {PagedItem, Pager} from './pagers';\nimport * as types from './types';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference] (https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference] (https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-1.5-flash',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: 'gemini-1.5-flash'});\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: 'gemini-1.5-flash'});\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromVertex();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromMldev();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: 'gemini-1.5-flash',\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listCachedContentsResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listCachedContentsResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client';\nimport * as t from './_transformers';\nimport {Models} from './models';\nimport * as types from './types';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\n if (content.parts === undefined || content.parts.length === 0) {\n return false;\n }\n for (const part of content.parts) {\n if (part === undefined || Object.keys(part).length === 0) {\n return false;\n }\n if (part.text !== undefined && part.text === '') {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @remarks\n * Expects the history to start with a user turn and then alternate between\n * user and model turns.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n if (history[0].role !== 'user') {\n throw new Error('History must start with a user turn.');\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n let userInput = comprehensiveHistory[0];\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n userInput = comprehensiveHistory[i];\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(userInput);\n curatedHistory.push(...modelOutput);\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n params.history,\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(this.apiClient, params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(inputContent, modelOutput);\n return;\n })();\n await this.sendPromise;\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(this.apiClient, params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = streamResponse.then(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n return curated ? extractCuratedHistory(this.history) : this.history;\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role === 'model')\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n this.history.push(userInput);\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function listFilesConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n apiClient: ApiClient,\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(\n apiClient: ApiClient,\n fromObject: types.File,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(\n toObject,\n ['error'],\n fileStatusToMldev(apiClient, fromError),\n );\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(apiClient, fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'file'],\n t.tFileName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'file'],\n t.tFileName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n apiClient: ApiClient,\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(\n apiClient: ApiClient,\n fromObject: types.File,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(\n toObject,\n ['error'],\n fileStatusFromMldev(apiClient, fromError),\n );\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n if (Array.isArray(fromFiles)) {\n common.setValueByPath(\n toObject,\n ['files'],\n fromFiles.map((item) => {\n return fileFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['files'], fromFiles);\n }\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromHttpHeaders = common.getValueByPath(fromObject, ['httpHeaders']);\n if (fromHttpHeaders != null) {\n common.setValueByPath(toObject, ['httpHeaders'], fromHttpHeaders);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_files_converters';\nimport {PagedItem, Pager} from './pagers';\nimport * as types from './types';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `common.UploadFileParameters` interface.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: common.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(this.apiClient, response);\n return file as types.File;\n });\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(this.apiClient, apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteFileResponseFromMldev();\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function partToMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['videoMetadata']) !== undefined) {\n throw new Error('videoMetadata parameter is not supported in Gemini API.');\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['example']) !== undefined) {\n throw new Error('example parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['pattern']) !== undefined) {\n throw new Error('pattern parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['default']) !== undefined) {\n throw new Error('default parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxLength']) !== undefined) {\n throw new Error('maxLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minLength']) !== undefined) {\n throw new Error('minLength parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['minProperties']) !== undefined) {\n throw new Error('minProperties parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['maxProperties']) !== undefined) {\n throw new Error('maxProperties parameter is not supported in Gemini API.');\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n apiClient: ApiClient,\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['response']) !== undefined) {\n throw new Error('response parameter is not supported in Gemini API.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToMldev(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToMldev());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(apiClient, fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(apiClient, fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(apiClient, t.tSchema(apiClient, fromResponseSchema)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n if (Array.isArray(fromSafetySettings)) {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings.map((item) => {\n return safetySettingToMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings,\n );\n }\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(\n apiClient,\n t.tTools(apiClient, fromTools).map((item) => {\n return toolToMldev(apiClient, t.tTool(apiClient, item));\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(apiClient, fromTools),\n );\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(apiClient, fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(\n apiClient,\n t.tSpeechConfig(apiClient, fromSpeechConfig),\n ),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(apiClient, fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToMldev(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(apiClient, fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n if (common.getValueByPath(fromObject, ['resolution']) !== undefined) {\n throw new Error('resolution parameter is not supported in Gemini API.');\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(apiClient, fromImage),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partToVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n apiClient: ApiClient,\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n apiClient: ApiClient,\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n schemaToVertex(apiClient, fromResponse),\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n apiClient: ApiClient,\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(apiClient, fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function toolToVertex(\n apiClient: ApiClient,\n fromObject: types.Tool,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n if (Array.isArray(fromFunctionDeclarations)) {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations.map((item) => {\n return functionDeclarationToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['functionDeclarations'],\n fromFunctionDeclarations,\n );\n }\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(toObject, ['googleSearch'], googleSearchToVertex());\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(apiClient, fromGoogleSearchRetrieval),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(apiClient, fromFunctionCallingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(apiClient, fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(apiClient, fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(apiClient, t.tSchema(apiClient, fromResponseSchema)),\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n if (Array.isArray(fromSafetySettings)) {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings.map((item) => {\n return safetySettingToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['safetySettings'],\n fromSafetySettings,\n );\n }\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(\n apiClient,\n t.tTools(apiClient, fromTools).map((item) => {\n return toolToVertex(apiClient, t.tTool(apiClient, item));\n }),\n ),\n );\n } else {\n common.setValueByPath(\n parentObject,\n ['tools'],\n t.tTools(apiClient, fromTools),\n );\n }\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(apiClient, fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(\n apiClient,\n t.tSpeechConfig(apiClient, fromSpeechConfig),\n ),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(apiClient, fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(apiClient, t.tContent(apiClient, fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n if (Array.isArray(fromTools)) {\n common.setValueByPath(\n parentObject,\n ['tools'],\n fromTools.map((item) => {\n return toolToVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(parentObject, ['tools'], fromTools);\n }\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n if (Array.isArray(fromContents)) {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(\n apiClient,\n t.tContents(apiClient, fromContents).map((item) => {\n return contentToVertex(apiClient, item);\n }),\n ),\n );\n } else {\n common.setValueByPath(\n toObject,\n ['contents'],\n t.tContents(apiClient, fromContents),\n );\n }\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(apiClient, fromImage),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function partFromMldev(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n apiClient: ApiClient,\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n apiClient: ApiClient,\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromMldev(apiClient, fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(apiClient, fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n if (Array.isArray(fromCandidates)) {\n common.setValueByPath(\n toObject,\n ['candidates'],\n fromCandidates.map((item) => {\n return candidateFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['candidates'], fromCandidates);\n }\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n apiClient: ApiClient,\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n if (Array.isArray(fromEmbeddings)) {\n common.setValueByPath(\n toObject,\n ['embeddings'],\n fromEmbeddings.map((item) => {\n return contentEmbeddingFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['embeddings'], fromEmbeddings);\n }\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['imageBytes'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n apiClient: ApiClient,\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['image'],\n imageFromMldev(apiClient, fromImage),\n );\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(apiClient, fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n if (Array.isArray(fromGeneratedImages)) {\n common.setValueByPath(\n toObject,\n ['generatedImages'],\n fromGeneratedImages.map((item) => {\n return generatedImageFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedImages'], fromGeneratedImages);\n }\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(apiClient, fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromMldev(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromMldev(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n apiClient: ApiClient,\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(toObject, ['fileData'], fromFileData);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(toObject, ['inlineData'], fromInlineData);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n apiClient: ApiClient,\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n if (Array.isArray(fromParts)) {\n common.setValueByPath(\n toObject,\n ['parts'],\n fromParts.map((item) => {\n return partFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['parts'], fromParts);\n }\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n apiClient: ApiClient,\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n apiClient: ApiClient,\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(apiClient, fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(apiClient, fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n if (Array.isArray(fromCandidates)) {\n common.setValueByPath(\n toObject,\n ['candidates'],\n fromCandidates.map((item) => {\n return candidateFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['candidates'], fromCandidates);\n }\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n apiClient: ApiClient,\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n apiClient: ApiClient,\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(apiClient, fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n if (Array.isArray(fromEmbeddings)) {\n common.setValueByPath(\n toObject,\n ['embeddings'],\n fromEmbeddings.map((item) => {\n return contentEmbeddingFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['embeddings'], fromEmbeddings);\n }\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(apiClient, fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n apiClient: ApiClient,\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['imageBytes'],\n t.tBytes(apiClient, fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n apiClient: ApiClient,\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['image'],\n imageFromVertex(apiClient, fromImage),\n );\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(apiClient, fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n if (Array.isArray(fromGeneratedImages)) {\n common.setValueByPath(\n toObject,\n ['generatedImages'],\n fromGeneratedImages.map((item) => {\n return generatedImageFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedImages'], fromGeneratedImages);\n }\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(apiClient, fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromVertex(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, ['response']);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromVertex(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as types from '../types';\nimport {\n contentFromMldev,\n contentFromVertex,\n contentToMldev,\n contentToVertex,\n toolToMldev,\n toolToVertex,\n} from './_models_converters';\n\n/**\n * Converters for live client.\n */\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): types.LiveClientMessage {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig !== undefined && fromConfig !== null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveConnectConfigToMldev(apiClient, fromConfig),\n );\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel !== undefined) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): types.LiveClientMessage {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig !== undefined && fromConfig !== null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveConnectConfigToVertex(apiClient, fromConfig),\n );\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel !== undefined) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerMessage,\n): types.LiveServerMessage {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete !== undefined) {\n common.setValueByPath(toObject, ['setupComplete'], fromSetupComplete);\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent !== undefined && fromServerContent !== null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(apiClient, fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall !== undefined && fromToolCall !== null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(apiClient, fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (\n fromToolCallCancellation !== undefined &&\n fromToolCallCancellation !== null\n ) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(\n apiClient,\n fromToolCallCancellation,\n ),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerMessage,\n): types.LiveServerMessage {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete !== undefined) {\n common.setValueByPath(toObject, ['setupComplete'], fromSetupComplete);\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent !== undefined && fromServerContent !== null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(apiClient, fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall !== undefined && fromToolCall !== null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(apiClient, fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (\n fromToolCallCancellation !== undefined &&\n fromToolCallCancellation !== null\n ) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(\n apiClient,\n fromToolCallCancellation,\n ),\n );\n }\n\n return toObject;\n}\n\nfunction liveConnectConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConfig,\n): types.LiveClientSetup {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig !== undefined) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'speechConfig'],\n fromSpeechConfig,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(apiClient, fromSystemInstruction),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (\n fromTools !== undefined &&\n fromTools !== null &&\n Array.isArray(fromTools)\n ) {\n common.setValueByPath(\n toObject,\n ['tools'],\n fromTools.map((item: types.Tool) => {\n return toolToMldev(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveConnectConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConfig,\n): types.LiveClientSetup {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig !== undefined) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n } else {\n // Set default to AUDIO to align with MLDev API.\n common.setValueByPath(\n toObject,\n ['generationConfig', 'responseModalities'],\n ['AUDIO'],\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig !== undefined) {\n common.setValueByPath(\n toObject,\n ['generationConfig', 'speechConfig'],\n fromSpeechConfig,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction !== undefined && fromSystemInstruction !== null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(apiClient, fromSystemInstruction),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (\n fromTools !== undefined &&\n fromTools !== null &&\n Array.isArray(fromTools)\n ) {\n common.setValueByPath(\n toObject,\n ['tools'],\n fromTools.map((item: types.Tool) => {\n return toolToVertex(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerContentFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerContent,\n): types.LiveServerContent {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn !== undefined && fromModelTurn !== null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(apiClient, fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete !== undefined) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted !== undefined) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n return toObject;\n}\n\nfunction liveServerContentFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerContent,\n): types.LiveServerContent {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn !== undefined && fromModelTurn !== null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(apiClient, fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete !== undefined) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted !== undefined) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n return toObject;\n}\n\nfunction functionCallFromMldev(\n apiClient: ApiClient,\n fromObject: types.FunctionCall,\n): types.FunctionCall {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId !== undefined) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs !== undefined) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName !== undefined) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nfunction functionCallFromVertex(\n apiClient: ApiClient,\n fromObject: types.FunctionCall,\n): types.FunctionCall {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs !== undefined) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName !== undefined) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCall,\n): types.LiveServerToolCall {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (\n fromFunctionCalls !== undefined &&\n fromFunctionCalls !== null &&\n Array.isArray(fromFunctionCalls)\n ) {\n common.setValueByPath(\n toObject,\n ['functionCalls'],\n fromFunctionCalls.map((item: types.FunctionCall) => {\n return functionCallFromMldev(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCall,\n): types.LiveServerToolCall {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (\n fromFunctionCalls !== undefined &&\n fromFunctionCalls !== null &&\n Array.isArray(fromFunctionCalls)\n ) {\n common.setValueByPath(\n toObject,\n ['functionCalls'],\n fromFunctionCalls.map((item: types.FunctionCall) => {\n return functionCallFromVertex(apiClient, item);\n }),\n );\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallCancellationFromMldev(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCallCancellation,\n): types.LiveServerToolCallCancellation {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds !== undefined) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nfunction liveServerToolCallCancellationFromVertex(\n apiClient: ApiClient,\n fromObject: types.LiveServerToolCallCancellation,\n): types.LiveServerToolCallCancellation {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds !== undefined) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client';\nimport {Auth} from './_auth';\nimport * as t from './_transformers';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket';\nimport * as converters from './converters/_live_converters';\nimport {contentToMldev, contentToVertex} from './converters/_models_converters';\nimport * as types from './types';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n let serverMessage: types.LiveServerMessage;\n let data: types.LiveServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveServerMessage;\n }\n if (apiClient.isVertexAI()) {\n serverMessage = converters.liveServerMessageFromVertex(apiClient, data);\n } else {\n serverMessage = converters.liveServerMessageFromMldev(apiClient, data);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental\n\n @remarks\n If using the Gemini API, Live is currently only supported behind API\n version `v1alpha`. Ensure that the API version is set to `v1alpha` when\n initializing the SDK if relying on the Gemini API.\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n const session = await ai.live.connect({\n model: 'gemini-2.0-flash-exp',\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateContent?key=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: types.LiveClientMessage = {};\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(\n apiClient,\n params.turns as types.ContentListUnion,\n );\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(apiClient, item));\n } else {\n contents = contents.map((item) => contentToMldev(apiClient, item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClientRealtimeInput(\n apiClient: ApiClient,\n params: types.LiveSendRealtimeInputParameters,\n ): types.LiveClientMessage {\n let clientMessage: types.LiveClientMessage = {};\n if (!('media' in params) || !params.media) {\n throw new Error(\n `Failed to convert realtime input \"media\", type: '${typeof params.media}'`,\n );\n }\n\n // LiveClientRealtimeInput\n clientMessage = {realtimeInput: {mediaChunks: [params.media]}};\n return clientMessage;\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n if (params.media == null) {\n throw new Error('Media is required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClientRealtimeInput(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n const session = await ai.live.connect({\n model: 'gemini-2.0-flash-exp',\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_models_converters';\nimport * as types from './types';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n return await this.generateContentInternal(params);\n };\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n return await this.generateContentStreamInternal(params);\n };\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param model - The model to use.\n * @param prompt - A text description of the image to generate.\n * @param [config] - The config for image generation.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n };\n }\n return response;\n });\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n apiClient,\n chunk,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n apiClient,\n chunk,\n );\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(\n this.apiClient,\n apiResponse,\n );\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.get({operation: operation});\n * }\n *\n * console.log(operation.result?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n async generateVideos(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client';\nimport * as common from '../_common';\nimport * as t from '../_transformers';\nimport * as types from '../types';\n\nexport function getOperationParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromMldev(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromMldev(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromMldev(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n apiClient: ApiClient,\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['videoBytes'],\n t.tBytes(apiClient, fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n apiClient: ApiClient,\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['video'],\n videoFromVertex(apiClient, fromVideo),\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n if (Array.isArray(fromGeneratedVideos)) {\n common.setValueByPath(\n toObject,\n ['generatedVideos'],\n fromGeneratedVideos.map((item) => {\n return generatedVideoFromVertex(apiClient, item);\n }),\n );\n } else {\n common.setValueByPath(toObject, ['generatedVideos'], fromGeneratedVideos);\n }\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResult = common.getValueByPath(fromObject, ['response']);\n if (fromResult != null) {\n common.setValueByPath(\n toObject,\n ['result'],\n generateVideosResponseFromVertex(apiClient, fromResult),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client';\nimport * as common from './_common';\nimport {BaseModule} from './_common';\nimport * as converters from './converters/_operations_converters';\nimport * as types from './types';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param operation The Operation object returned by a previous API call.\n * @return The updated Operation object, with the latest status or result.\n */\n async get(\n parameters: types.OperationGetParameters,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n var httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n return this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n } else {\n return this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n const body = converters.getOperationParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(\n this.apiClient,\n apiResponse,\n );\n\n return resp as types.GenerateVideosOperation;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth';\nimport * as common from './_common';\nimport {Uploader} from './_uploader';\nimport {File, HttpOptions, HttpResponse, UploadFileConfig} from './types';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst USER_AGENT_HEADER = 'User-Agent';\nconst GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '0.7.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Client errors raised by the GenAI API.\n */\nexport class ClientError extends Error {\n constructor(message: string, stackTrace?: string) {\n if (stackTrace) {\n super(message, {cause: stackTrace});\n } else {\n super(message, {cause: new Error().stack});\n }\n this.message = message;\n this.name = 'ClientError';\n }\n}\n\n/**\n * Server errors raised by the GenAI API.\n */\nexport class ServerError extends Error {\n constructor(message: string, stackTrace?: string) {\n if (stackTrace) {\n super(message, {cause: stackTrace});\n } else {\n super(message, {cause: new Error().stack});\n }\n this.message = message;\n this.name = 'ServerError';\n }\n}\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n // Assume that proj/api key validation occurs before they are passed in.\n if (this.getProject() || this.getLocation()) {\n initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n this.clientOptions.apiKey = undefined; // unset API key.\n } else {\n initHttpOptions.baseUrl = `https://aiplatform.googleapis.com/`;\n this.clientOptions.project = undefined; // unset project.\n this.clientOptions.location = undefined; // unset location.\n }\n } else {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(path: string, httpOptions: HttpOptions): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (\n this.clientOptions.vertexai &&\n !this.clientOptions.apiKey &&\n !path.startsWith('projects/')\n ) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const url = this.constructUrl(request.path, patchedHttpOptions);\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const url = this.constructUrl(request.path, patchedHttpOptions);\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n ): Promise {\n if (httpOptions && httpOptions.timeout && httpOptions.timeout > 0) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n setTimeout(() => abortController.abort(), httpOptions.timeout);\n requestInit.signal = signal;\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n // TODO: Replace with HttpResponse.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value);\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const chunkData = JSON.parse(processedChunkString);\n yield chunkData;\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new ServerError('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n const statusText: string = response.statusText;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: 'exception parsing response',\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = `got status: ${status} ${statusText}. ${JSON.stringify(\n errorBody,\n )}`;\n if (status >= 400 && status < 500) {\n const clientError = new ClientError(errorMessage);\n throw clientError;\n } else if (status >= 500 && status < 600) {\n const serverError = new ServerError(errorMessage);\n throw serverError;\n }\n throw new Error(errorMessage);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client';\nimport {FileStat, Uploader} from '../_uploader';\nimport {File, HttpResponse} from '../types';\n\nimport {crossError} from './_cross_error';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.['x-goog-upload-status'] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.['x-goog-upload-status'] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client';\nimport {FileStat, Uploader} from '../_uploader';\nimport {getBlobStat, uploadBlob} from '../cross/_cross_uploader';\nimport {File} from '../types';\n\nexport class BrowserUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw new Error('File path is not supported in browser uploader.');\n }\n\n return await uploadBlob(file, uploadUrl, apiClient);\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw new Error('File path is not supported in browser uploader.');\n } else {\n return await getBlobStat(file);\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n WebSocketCallbacks,\n WebSocketFactory,\n WebSocket as Ws,\n} from '../_websocket';\n\n// TODO((b/401271082): re-enable lint once BrowserWebSocketFactory is\n// implemented.\n/* eslint-disable @typescript-eslint/no-unused-vars */\nexport class BrowserWebSocketFactory implements WebSocketFactory {\n create(\n url: string,\n headers: Record,\n callbacks: WebSocketCallbacks,\n ): Ws {\n return new BrowserWebSocket(url, headers, callbacks);\n }\n}\n\nexport class BrowserWebSocket implements Ws {\n private ws?: WebSocket;\n\n constructor(\n private readonly url: string,\n private readonly headers: Record,\n private readonly callbacks: WebSocketCallbacks,\n ) {}\n\n connect(): void {\n this.ws = new WebSocket(this.url);\n\n this.ws.onopen = this.callbacks.onopen;\n this.ws.onerror = this.callbacks.onerror;\n this.ws.onclose = this.callbacks.onclose;\n this.ws.onmessage = this.callbacks.onmessage;\n }\n\n send(message: string) {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.send(message);\n }\n\n close() {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.close();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from '../_auth';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\n// TODO(b/395122533): We need a secure client side authentication mechanism.\nexport class WebAuth implements Auth {\n constructor(private readonly apiKey: string) {}\n\n async addAuthHeaders(headers: Headers): Promise {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client';\nimport {Caches} from '../caches';\nimport {Chats} from '../chats';\nimport {GoogleGenAIOptions} from '../client';\nimport {Files} from '../files';\nimport {Live} from '../live';\nimport {Models} from '../models';\nimport {Operations} from '../operations';\n\nimport {BrowserUploader} from './_browser_uploader';\nimport {BrowserWebSocketFactory} from './_browser_websocket';\nimport {WebAuth} from './_web_auth';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link\n * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or\n * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI\n * API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API\n * services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be\n * set. When using Vertex AI, currently only {@link GoogleGenAIOptions.apiKey}\n * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link\n * GoogleGenAIOptions.location} should not be set.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n\n constructor(options: GoogleGenAIOptions) {\n if (options.apiKey == null) {\n throw new Error('An API Key must be set when running in a browser');\n }\n // Web client only supports API key mode for Vertex AI.\n if (options.project || options.location) {\n throw new Error(\n 'Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.',\n );\n }\n this.vertexai = options.vertexai ?? false;\n\n this.apiKey = options.apiKey;\n this.apiVersion = options.apiVersion;\n const auth = new WebAuth(this.apiKey);\n this.apiClient = new ApiClient({\n auth: auth,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + 'web',\n uploader: new BrowserUploader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory());\n this.chats = new Chats(this.models, this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n }\n}\n"],"names":["partToMldev","common.getValueByPath","common.setValueByPath","contentToMldev","functionDeclarationToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","toolToMldev","functionCallingConfigToMldev","toolConfigToMldev","t.tContents","t.tContent","t.tCachesModel","t.tCachedContentName","partToVertex","contentToVertex","schemaToVertex","functionDeclarationToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","toolToVertex","functionCallingConfigToVertex","toolConfigToVertex","converters.createCachedContentParametersToVertex","common.formatMap","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","t.tSchema","t.tTools","t.tTool","t.tSpeechConfig","t.tModel","t.tContentsForEmbed","t.tBytes","videoFromMldev","generatedVideoFromMldev","generateVideosResponseFromMldev","generateVideosOperationFromMldev","videoFromVertex","generatedVideoFromVertex","generateVideosResponseFromVertex","generateVideosOperationFromVertex","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","types.GenerateContentResponse","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex"],"mappings":"AAAA;;;;AAIG;MAIU,UAAU,CAAA;AAAG;AAWV,SAAA,SAAS,CACvB,cAAsB,EACtB,QAAiC,EAAA;;IAGjC,MAAM,KAAK,GAAG,cAAc;;IAG5B,OAAO,cAAc,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,GAAG,KAAI;AAClD,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE;AACvD,YAAA,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC;;AAE3B,YAAA,OAAO,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;AAClE;AAAM,aAAA;;AAEL,YAAA,MAAM,IAAI,KAAK,CAAC,QAAQ,GAAG,CAAA,wBAAA,CAA0B,CAAC;AACvD;AACH,KAAC,CAAC;AACJ;SAEgB,cAAc,CAC5B,IAA6B,EAC7B,IAAc,EACd,KAAc,EAAA;AAEd,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AACxC,QAAA,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC;AAEnB,QAAA,IAAI,GAAG,CAAC,QAAQ,CAAC,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ACF,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;AACxC,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,uBAAuB,EAAE,CAAC;AACzE,QAAA,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC;QACnD,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QACxC,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC;QACtC,IAAI,CAAC,UAAU,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC;;AAEnD;;;;"} \ No newline at end of file diff --git a/node_modules/@google/genai/dist/web/web.d.ts b/node_modules/@google/genai/dist/web/web.d.ts new file mode 100644 index 0000000..1c9ba7b --- /dev/null +++ b/node_modules/@google/genai/dist/web/web.d.ts @@ -0,0 +1,3663 @@ +import { GoogleAuthOptions } from 'google-auth-library'; + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * 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 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, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +declare class BaseModule { +} + +/** Content blob. */ +declare interface Blob_2 { + /** Required. Raw bytes. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob } + +export declare enum BlockedReason { + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + SAFETY = "SAFETY", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT" +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: (params?: types.ListCachedContentsParameters) => Promise>; + /** + * 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 [Vertex AI 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-1.5-flash', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create(params: types.CreateCachedContentParameters): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: 'gemini-1.5-flash'}); + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * 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: 'gemini-1.5-flash'}); + * ``` + */ + delete(params: types.DeleteCachedContentParameters): Promise; + /** + * 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: 'gemini-1.5-flash', + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update(params: types.UpdateCachedContentParameters): Promise; + private listInternal; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor(apiClient: ApiClient, modelsModule: Models, model: string, config?: types.GenerateContentConfig, history?: types.Content[]); + /** + * 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); + * ``` + */ + sendMessage(params: types.SendMessageParameters): Promise; + /** + * 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); + * } + * ``` + */ + sendMessageStream(params: types.SendMessageParameters): Promise>; + /** + * 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?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, 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: types.CreateChatParameters): Chat; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +declare namespace common { + export { + formatMap, + setValueByPath, + getValueByPath, + BaseModule, + UploadFileParameters + } +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + left blank or unset. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = ContentUnion[] | ContentUnion; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** 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. + */ +export declare interface ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; +} + +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH" +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-1.5-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-1.5-pro', etc. See gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent(partOrString: PartListUnion | string): Content; + +/** + * Creates a `Part` object from a `base64` `string`. + */ +export declare function createPartFromBase64(data: string, mimeType: string): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult(outcome: Outcome, output: string): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode(code: string, language: Language): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall(name: string, args: Record): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse(id: string, name: string, response: Record): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent(partOrString: PartListUnion | string): Content; + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse { +} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse { +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +export declare enum DynamicRetrievalConfigMode { + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [FunctionDeclaration] tool and [FunctionCallingConfig] mode is set to [Mode.CODE]. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File } + +/** URI based data. */ +export declare interface FileData { + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in 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. + * Somex eamples 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 + * `common.UploadFileParameters` interface. + * @return A promise that resolves to a `types.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, + * 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); + * ``` + */ + upload(params: common.UploadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * 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); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * 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}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED" +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED" +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +export declare enum FinishReason { + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + STOP = "STOP", + MAX_TOKENS = "MAX_TOKENS", + SAFETY = "SAFETY", + RECITATION = "RECITATION", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + SPII = "SPII", + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + IMAGE_SAFETY = "IMAGE_SAFETY" +} + +declare function formatMap(templateString: string, valueMap: Record): string; + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. Required. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +export declare enum FunctionCallingConfigMode { + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + AUTO = "AUTO", + ANY = "ANY", + NONE = "NONE" +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Describes the output from the function in the OpenAPI JSON Schema + Object format. */ + response?: Schema; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; +} + +/** A function response. */ +export declare class FunctionResponse { + /** The id of the function call this response is for. Populated by the client + to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response media type of the generated candidate text. + */ + responseMimeType?: string; + /** Schema that the generated candidate text must adhere to. + */ + responseSchema?: SchemaUnion; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** Identifier for each response. + */ + responseId?: string; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * 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(): string | 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(): FunctionCall[] | undefined; + /** + * 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(): string | undefined; + /** + * 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(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. + */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. + */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. + */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. + */ + enhancedPrompt?: string; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** Whether to use the prompt rewriting logic. + */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** List of generated images. + */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. + */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 1280x720, 1920x1080 are supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation progress. */ + pubsubTopic?: string; + /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** A video generation operation. */ +export declare interface GenerateVideosOperation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The normal response of the operation in case of success. */ + response?: Record; + /** The generated videos. */ + result?: GenerateVideosResponse; +} + +/** Class that represents the parameters for generating an image. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. Optional for image to video use cases. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt is provided. */ + image?: Image_2; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: 'UNKNOWN' | 'PRIORITIZE_QUALITY' | 'BALANCED' | 'PRIORITIZE_COST'; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. e.g. 'gemini-1.5-pro-001'. */ + modelName?: string; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +declare function getValueByPath(data: unknown, keys: string[]): unknown; + +/** + * 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, currently only {@link GoogleGenAIOptions.apiKey} + * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} should not be set. + * + * @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' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project region for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. This list must have the same size as the grounding_chunk_indices. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +export declare enum HarmBlockMethod { + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + SEVERITY = "SEVERITY", + PROBABILITY = "PROBABILITY" +} + +export declare enum HarmBlockThreshold { + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE", + OFF = "OFF" +} + +export declare enum HarmCategory { + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY" +} + +export declare enum HarmProbability { + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + NEGLIGIBLE = "NEGLIGIBLE", + LOW = "LOW", + MEDIUM = "MEDIUM", + HIGH = "HIGH" +} + +export declare enum HarmSeverity { + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH" +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE'; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. + */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image } + +export declare enum ImagePromptLanguage { + auto = "auto", + en = "en", + ja = "ja", + ko = "ko", + hi = "hi" +} + +export declare enum Language { + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + PYTHON = "PYTHON" +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental + + @remarks + If using the Gemini API, Live is currently only supported behind API + version `v1alpha`. Ensure that the API version is set to `v1alpha` when + initializing the SDK if relying on the Gemini API. + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + 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.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + onopen?: (() => void) | null; + onmessage: (e: LiveServerMessage) => void; + onerror?: ((e: ErrorEvent) => void) | null; + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `ClientContentUpdate` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `ClientContentUpdate` and the `RealtimeUpdate`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + + The following fields are supported: + - `response_logprobs` + - `response_mime_type` + - `logprobs` + - `response_schema` + - `stop_sequence` + - `routing_config` + - `audio_timestamp` + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: Content; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; +} + +/** 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. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: Content; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media: Blob_2; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; +} + +/** Response message for API call. */ +export declare interface LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; +} + +/** Sent in response to a `LiveGenerateContentSetup` message from the client. */ +export declare interface LiveServerSetupComplete { +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** 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. + */ +export declare interface MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; +} + +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC" +} + +export declare enum MediaModality { + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + TEXT = "TEXT", + IMAGE = "IMAGE", + VIDEO = "VIDEO", + AUDIO = "AUDIO", + DOCUMENT = "DOCUMENT" +} + +export declare enum MediaResolution { + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH" +} + +export declare enum Modality { + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + TEXT = "TEXT", + IMAGE = "IMAGE", + AUDIO = "AUDIO" +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +export declare enum Mode { + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI 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); + * ``` + */ + generateContent: (params: types.GenerateContentParameters) => Promise; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI 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); + * } + * ``` + */ + generateContentStream: (params: types.GenerateContentParameters) => Promise>; + /** + * Generates an image based on a text description and configuration. + * + * @param model - The model to use. + * @param prompt - A text description of the image to generate. + * @param [config] - The config for image generation. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: (params: types.GenerateImagesParameters) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * 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); + * ``` + */ + embedContent(params: types.EmbedContentParameters): Promise; + /** + * 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 ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + private generateImagesInternal; + /** + * 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); + * ``` + */ + countTokens(params: types.CountTokensParameters): Promise; + /** + * 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); + * ``` + */ + computeTokens(params: types.ComputeTokensParameters): Promise; + /** + * 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', + * 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.get({operation: operation}); + * } + * + * console.log(operation.result?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos(params: types.GenerateVideosParameters): Promise; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters { + /** The operation to be retrieved. */ + operation: GenerateVideosOperation; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param operation The Operation object returned by a previous API call. + * @return The updated Operation object, with the latest status or result. + */ + get(parameters: types.OperationGetParameters): Promise; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +export declare enum Outcome { + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + OUTCOME_OK = "OUTCOME_OK", + OUTCOME_FAILED = "OUTCOME_FAILED", + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED" +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Pagers for the GenAI List APIs. + */ +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents" +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + protected requestInternal: (params: PagedItemConfig) => Promise>; + protected idxInternal: number; + constructor(name: PagedItem, request: (params: PagedItemConfig) => Promise>, response: PagedItemResponse, params: PagedItemConfig); + private init; + private initNextPage; + /** + * 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(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * 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(): number; + /** + * 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(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * 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](): AsyncIterator; + /** + * 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(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. URI based data. */ + fileData?: FileData; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +export declare type PartUnion = Part | string; + +export declare enum PersonGeneration { + DONT_ALLOW = "DONT_ALLOW", + ALLOW_ADULT = "ALLOW_ADULT", + ALLOW_ALL = "ALLOW_ALL" +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. + */ + voiceName?: string; +} + +/** 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. + */ +export declare interface RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. + */ + categories?: string[]; + /** List of scores of each categories. + */ + scores?: number[]; + /** Internal use only. + */ + contentType?: string; +} + +export declare enum SafetyFilterLevel { + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE" +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Schema that defines the format of input and output data. + + Represents a select subset of an OpenAPI 3.0 schema object. + */ +export declare interface Schema { + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema; + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClientRealtimeInput; + private tLiveClienttToolResponse; + /** + 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: types.LiveSendClientContentParameters): void; + /** + 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: types.LiveSendRealtimeInputParameters): void; + /** + 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: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + const session = await ai.live.connect({ + model: 'gemini-2.0-flash-exp', + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +declare function setValueByPath(data: Record, keys: string[], value: unknown): void; + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +export declare enum State { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + ACTIVE = "ACTIVE", + ERROR = "ERROR" +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** 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. + */ +export declare interface StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** 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. + */ +export declare interface SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; +} + +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT" +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional. Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. This field is only used by the Gemini Developer API services. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution { +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; +} + +export declare type ToolListUnion = Tool[]; + +export declare enum Type { + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + STRING = "STRING", + NUMBER = "NUMBER", + INTEGER = "INTEGER", + BOOLEAN = "BOOLEAN", + ARRAY = "ARRAY", + OBJECT = "OBJECT" +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + Modality, + State, + DynamicRetrievalConfigMode, + FunctionCallingConfigMode, + MediaResolution, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + FileState, + FileSource, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + MediaModality, + VideoMetadata, + CodeExecutionResult, + ExecutableCode, + FileData, + FunctionCall, + FunctionResponse, + Blob_2 as Blob, + Part, + Content, + HttpOptions, + Schema, + SafetySetting, + FunctionDeclaration, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + VertexAISearch, + VertexRagStoreRagResource, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeechConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + GoogleTypeDate, + Citation, + CitationMetadata, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + GenerateVideosConfig, + GenerateVideosParameters, + Video, + GeneratedVideo, + GenerateVideosResponse, + GenerateVideosOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + HttpResponse, + LiveCallbacks, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceConfig, + MaskReferenceImage, + ControlReferenceConfig, + ControlReferenceImage, + StyleReferenceConfig, + StyleReferenceImage, + SubjectReferenceConfig, + SubjectReferenceImage, + LiveServerSetupComplete, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + LiveServerMessage, + LiveClientSetup, + LiveClientContent, + LiveClientRealtimeInput, + LiveClientToolResponse, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendRealtimeInputParameters, + LiveSendToolResponseParameters, + OperationGetParameters, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolListUnion + } +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload(file: string | Blob, uploadUrl: string, apiClient: ApiClient): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression if the ``output_mime_type`` is + ``image/jpeg``. */ + outputCompressionQuality?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. */ + videoBytes?: string; + /** Video encoding, for example "video/mp4". */ + mimeType?: string; +} + +/** Metadata describes the input video content. */ +export declare interface VideoMetadata { + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create(url: string, headers: Record, callbacks: WebSocketCallbacks): WebSocket_2; +} + +export { } diff --git a/node_modules/@google/genai/node/package.json b/node_modules/@google/genai/node/package.json new file mode 100644 index 0000000..7666aff --- /dev/null +++ b/node_modules/@google/genai/node/package.json @@ -0,0 +1,4 @@ +{ + "name": "@google/genai/node", + "main": "../dist/node/index.js" +} diff --git a/node_modules/@google/genai/package.json b/node_modules/@google/genai/package.json new file mode 100644 index 0000000..5de3375 --- /dev/null +++ b/node_modules/@google/genai/package.json @@ -0,0 +1,106 @@ +{ + "name": "@google/genai", + "version": "0.7.0", + "description": "", + "main": "dist/node/index.js", + "module": "dist/web/index.mjs", + "browser": "dist/web/index.mjs", + "typings": "dist/genai.d.ts", + "exports": { + ".": { + "browser": { + "types": "./dist/web/web.d.ts", + "import": "./dist/web/index.mjs", + "default": "./dist/web/index.mjs" + }, + "node": { + "types": "./dist/node/node.d.ts", + "require": "./dist/node/index.js", + "default": "./dist/node/index.js" + }, + "types": "./dist/genai.d.ts", + "require": "./dist/index.js", + "import": "./dist/index.mjs", + "default": "./dist/index.js" + }, + "./web": { + "types": "./dist/web/web.d.ts", + "import": "./dist/web/index.mjs", + "default": "./dist/web/index.mjs" + }, + "./node": { + "types": "./dist/node/node.d.ts", + "require": "./dist/node/index.js", + "default": "./dist/node/index.js" + } + }, + "scripts": { + "prepare": "npm run build-prod", + "build": "rollup -c && api-extractor run --local --verbose && api-extractor run -c api-extractor.node.json --local --verbose&& api-extractor run -c api-extractor.web.json --local --verbose", + "build-prod": "rollup -c && api-extractor run --verbose && api-extractor run -c api-extractor.node.json --verbose && api-extractor run -c api-extractor.web.json --verbose", + "unit-test": "ts-node node_modules/jasmine/bin/jasmine test/unit/**/*_test.ts test/unit/*_test.ts", + "system-test": "ts-node node_modules/jasmine/bin/jasmine test/system/**/*_test.ts", + "docs": "typedoc && ts-node scripts/add_docsite_license_headers.ts", + "format": "prettier '**/*.ts' '**/*.mjs' '**/*.json' --write", + "lint": "eslint '**/*.ts'", + "lint-fix": "eslint --fix '**/*.ts'" + }, + "engines": { + "node": ">=18.0.0" + }, + "files": [ + "dist/genai.d.ts", + "dist/index.js", + "dist/index.js.map", + "dist/index.mjs", + "dist/index.mjs.map", + "dist/node/index.js", + "dist/node/index.js.map", + "dist/node/index.mjs", + "dist/node/index.mjs.map", + "dist/node/node.d.ts", + "dist/web/index.js", + "dist/web/index.js.map", + "dist/web/index.mjs", + "dist/web/index.mjs.map", + "dist/web/web.d.ts", + "node/package.json", + "web/package.json" + ], + "devDependencies": { + "@eslint/js": "9.20.0", + "@microsoft/api-extractor": "^7.50.1", + "@rollup/plugin-json": "^6.1.0", + "@types/jasmine": "^5.1.2", + "@types/node": "^20.9.0", + "@types/unist": "^3.0.3", + "@types/ws": "^8.5.14", + "eslint": "8.57.0", + "gts": "^5.2.0", + "jasmine": "^5.5.0", + "jasmine-reporters": "^2.4.0", + "nyc": "^17.1.0", + "prettier": "3.3.3", + "prettier-plugin-organize-imports": "^4.1.0", + "rollup-plugin-typescript2": "^0.36.0", + "ts-node": "^10.9.2", + "tslib": "^2.8.1", + "typedoc": "^0.27.0", + "typescript": "~5.2.0", + "typescript-eslint": "8.24.1" + }, + "dependencies": { + "google-auth-library": "^9.14.2", + "ws": "^8.18.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/googleapis/js-genai.git" + }, + "bugs": { + "url": "https://github.com/googleapis/js-genai/issues" + }, + "homepage": "https://github.com/googleapis/js-genai#readme", + "author": "", + "license": "Apache-2.0" +} diff --git a/node_modules/@google/genai/web/package.json b/node_modules/@google/genai/web/package.json new file mode 100644 index 0000000..606dd1f --- /dev/null +++ b/node_modules/@google/genai/web/package.json @@ -0,0 +1,4 @@ +{ + "name": "@google/genai/web", + "module": "../dist/web/index.mjs" +} diff --git a/node_modules/accepts/HISTORY.md b/node_modules/accepts/HISTORY.md new file mode 100644 index 0000000..cb5990c --- /dev/null +++ b/node_modules/accepts/HISTORY.md @@ -0,0 +1,243 @@ +1.3.8 / 2022-02-02 +================== + + * deps: mime-types@~2.1.34 + - deps: mime-db@~1.51.0 + * deps: negotiator@0.6.3 + +1.3.7 / 2019-04-29 +================== + + * deps: negotiator@0.6.2 + - Fix sorting charset, encoding, and language with extra parameters + +1.3.6 / 2019-04-28 +================== + + * deps: mime-types@~2.1.24 + - deps: mime-db@~1.40.0 + +1.3.5 / 2018-02-28 +================== + + * deps: mime-types@~2.1.18 + - deps: mime-db@~1.33.0 + +1.3.4 / 2017-08-22 +================== + + * deps: mime-types@~2.1.16 + - deps: mime-db@~1.29.0 + +1.3.3 / 2016-05-02 +================== + + * deps: mime-types@~2.1.11 + - deps: mime-db@~1.23.0 + * deps: negotiator@0.6.1 + - perf: improve `Accept` parsing speed + - perf: improve `Accept-Charset` parsing speed + - perf: improve `Accept-Encoding` parsing speed + - perf: improve `Accept-Language` parsing speed + +1.3.2 / 2016-03-08 +================== + + * deps: mime-types@~2.1.10 + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + - deps: mime-db@~1.22.0 + +1.3.1 / 2016-01-19 +================== + + * deps: mime-types@~2.1.9 + - deps: mime-db@~1.21.0 + +1.3.0 / 2015-09-29 +================== + + * deps: mime-types@~2.1.7 + - deps: mime-db@~1.19.0 + * deps: negotiator@0.6.0 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Lazy-load modules from main entry point + - perf: delay type concatenation until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove closures getting spec properties + - perf: remove a closure from media type parsing + - perf: remove property delete from media type parsing + +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +1.2.9 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - perf: fix deopt during mapping + +1.2.8 / 2015-06-07 +================== + + * deps: mime-types@~2.1.0 + - deps: mime-db@~1.13.0 + * perf: avoid argument reassignment & argument slice + * perf: avoid negotiator recursive construction + * perf: enable strict mode + * perf: remove unnecessary bitwise operator + +1.2.7 / 2015-05-10 +================== + + * deps: negotiator@0.5.3 + - Fix media type parameter matching to be case-insensitive + +1.2.6 / 2015-05-07 +================== + + * deps: mime-types@~2.0.11 + - deps: mime-db@~1.9.1 + * deps: negotiator@0.5.2 + - Fix comparing media types with quoted values + - Fix splitting media types with quoted commas + +1.2.5 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - deps: mime-db@~1.8.0 + +1.2.4 / 2015-02-14 +================== + + * Support Node.js 0.6 + * deps: mime-types@~2.0.9 + - deps: mime-db@~1.7.0 + * deps: negotiator@0.5.1 + - Fix preference sorting to be stable for long acceptable lists + +1.2.3 / 2015-01-31 +================== + + * deps: mime-types@~2.0.8 + - deps: mime-db@~1.6.0 + +1.2.2 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - deps: mime-db@~1.5.0 + +1.2.1 / 2014-12-30 +================== + + * deps: mime-types@~2.0.5 + - deps: mime-db@~1.3.1 + +1.2.0 / 2014-12-19 +================== + + * deps: negotiator@0.5.0 + - Fix list return order when large accepted list + - Fix missing identity encoding when q=0 exists + - Remove dynamic building of Negotiator class + +1.1.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/node_modules/accepts/LICENSE b/node_modules/accepts/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/accepts/README.md b/node_modules/accepts/README.md new file mode 100644 index 0000000..82680c5 --- /dev/null +++ b/node_modules/accepts/README.md @@ -0,0 +1,140 @@ +# accepts + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). +Extracted from [koa](https://www.npmjs.com/package/koa) for general use. + +In addition to negotiator, it allows: + +- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` + as well as `('text/html', 'application/json')`. +- Allows type shorthands such as `json`. +- Returns `false` when no types match +- Treats non-existent headers as `*` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install accepts +``` + +## API + +```js +var accepts = require('accepts') +``` + +### accepts(req) + +Create a new `Accepts` object for the given `req`. + +#### .charset(charsets) + +Return the first accepted charset. If nothing in `charsets` is accepted, +then `false` is returned. + +#### .charsets() + +Return the charsets that the request accepts, in the order of the client's +preference (most preferred first). + +#### .encoding(encodings) + +Return the first accepted encoding. If nothing in `encodings` is accepted, +then `false` is returned. + +#### .encodings() + +Return the encodings that the request accepts, in the order of the client's +preference (most preferred first). + +#### .language(languages) + +Return the first accepted language. If nothing in `languages` is accepted, +then `false` is returned. + +#### .languages() + +Return the languages that the request accepts, in the order of the client's +preference (most preferred first). + +#### .type(types) + +Return the first accepted type (and it is returned as the same text as what +appears in the `types` array). If nothing in `types` is accepted, then `false` +is returned. + +The `types` array can contain full MIME types or file extensions. Any value +that is not a full MIME types is passed to `require('mime-types').lookup`. + +#### .types() + +Return the types that the request accepts, in the order of the client's +preference (most preferred first). + +## Examples + +### Simple type negotiation + +This simple example shows how to use `accepts` to return a different typed +respond body based on what the client wants to accept. The server lists it's +preferences in order and will get back the best match between the client and +server. + +```js +var accepts = require('accepts') +var http = require('http') + +function app (req, res) { + var accept = accepts(req) + + // the order of this list is significant; should be server preferred order + switch (accept.type(['json', 'html'])) { + case 'json': + res.setHeader('Content-Type', 'application/json') + res.write('{"hello":"world!"}') + break + case 'html': + res.setHeader('Content-Type', 'text/html') + res.write('hello, world!') + break + default: + // the fallback is text/plain, so no need to specify it above + res.setHeader('Content-Type', 'text/plain') + res.write('hello, world!') + break + } + + res.end() +} + +http.createServer(app).listen(3000) +``` + +You can test this out with the cURL program: +```sh +curl -I -H'Accept: text/html' http://localhost:3000/ +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master +[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml +[node-version-image]: https://badgen.net/npm/node/accepts +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/accepts +[npm-url]: https://npmjs.org/package/accepts +[npm-version-image]: https://badgen.net/npm/v/accepts diff --git a/node_modules/accepts/index.js b/node_modules/accepts/index.js new file mode 100644 index 0000000..e9b2f63 --- /dev/null +++ b/node_modules/accepts/index.js @@ -0,0 +1,238 @@ +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Negotiator = require('negotiator') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = Accepts + +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } + + this.headers = req.headers + this.negotiator = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] + } + } + + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } + + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] + + return first + ? types[mimes.indexOf(first)] + : false +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } + + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } + + return this.negotiator.encodings(encodings)[0] || false +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ + + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } + } + + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() + } + + return this.negotiator.languages(languages)[0] || false +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ + +function validMime (type) { + return typeof type === 'string' +} diff --git a/node_modules/accepts/package.json b/node_modules/accepts/package.json new file mode 100644 index 0000000..0f2d15d --- /dev/null +++ b/node_modules/accepts/package.json @@ -0,0 +1,47 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "1.3.8", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/accepts", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ] +} diff --git a/node_modules/agent-base/LICENSE b/node_modules/agent-base/LICENSE new file mode 100644 index 0000000..008728c --- /dev/null +++ b/node_modules/agent-base/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/agent-base/README.md b/node_modules/agent-base/README.md new file mode 100644 index 0000000..b8a86b9 --- /dev/null +++ b/node_modules/agent-base/README.md @@ -0,0 +1,69 @@ +agent-base +========== +### Turn a function into an [`http.Agent`][http.Agent] instance + +This module is a thin wrapper around the base `http.Agent` class. + +It provides an abstract class that must define a `connect()` function, +which is responsible for creating the underlying socket that the HTTP +client requests will use. + +The `connect()` function may return an arbitrary `Duplex` stream, or +another `http.Agent` instance to delegate the request to, and may be +asynchronous (by defining an `async` function). + +Instances of this agent can be used with the `http` and `https` +modules. To differentiate, the options parameter in the `connect()` +function includes a `secureEndpoint` property, which can be checked +to determine what type of socket should be returned. + +#### Some subclasses: + +Here are some more interesting uses of `agent-base`. +Send a pull request to list yours! + + * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints + * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints + * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS + * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS + +Example +------- + +Here's a minimal example that creates a new `net.Socket` or `tls.Socket` +based on the `secureEndpoint` property. This agent can be used with both +the `http` and `https` modules. + +```ts +import * as net from 'net'; +import * as tls from 'tls'; +import * as http from 'http'; +import { Agent } from 'agent-base'; + +class MyAgent extends Agent { + connect(req, opts) { + // `secureEndpoint` is true when using the "https" module + if (opts.secureEndpoint) { + return tls.connect(opts); + } else { + return net.connect(opts); + } + } +}); + +// Keep alive enabled means that `connect()` will only be +// invoked when a new connection needs to be created +const agent = new MyAgent({ keepAlive: true }); + +// Pass the `agent` option when creating the HTTP request +http.get('http://nodejs.org/api/', { agent }, (res) => { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +[http-proxy-agent]: ../http-proxy-agent +[https-proxy-agent]: ../https-proxy-agent +[pac-proxy-agent]: ../pac-proxy-agent +[socks-proxy-agent]: ../socks-proxy-agent +[http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent diff --git a/node_modules/agent-base/dist/helpers.d.ts b/node_modules/agent-base/dist/helpers.d.ts new file mode 100644 index 0000000..b468f23 --- /dev/null +++ b/node_modules/agent-base/dist/helpers.d.ts @@ -0,0 +1,15 @@ +/// +/// +/// +/// +/// +import * as http from 'http'; +import * as https from 'https'; +import type { Readable } from 'stream'; +export type ThenableRequest = http.ClientRequest & { + then: Promise['then']; +}; +export declare function toBuffer(stream: Readable): Promise; +export declare function json(stream: Readable): Promise; +export declare function req(url: string | URL, opts?: https.RequestOptions): ThenableRequest; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/agent-base/dist/helpers.d.ts.map b/node_modules/agent-base/dist/helpers.d.ts.map new file mode 100644 index 0000000..9479c9a --- /dev/null +++ b/node_modules/agent-base/dist/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";;;;;AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAEvC,MAAM,MAAM,eAAe,GAAG,IAAI,CAAC,aAAa,GAAG;IAClD,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC;CAC5C,CAAC;AAEF,wBAAsB,QAAQ,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,CAQhE;AAGD,wBAAsB,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,CAUzD;AAED,wBAAgB,GAAG,CAClB,GAAG,EAAE,MAAM,GAAG,GAAG,EACjB,IAAI,GAAE,KAAK,CAAC,cAAmB,GAC7B,eAAe,CAcjB"} \ No newline at end of file diff --git a/node_modules/agent-base/dist/helpers.js b/node_modules/agent-base/dist/helpers.js new file mode 100644 index 0000000..ef3f920 --- /dev/null +++ b/node_modules/agent-base/dist/helpers.js @@ -0,0 +1,66 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.req = exports.json = exports.toBuffer = void 0; +const http = __importStar(require("http")); +const https = __importStar(require("https")); +async function toBuffer(stream) { + let length = 0; + const chunks = []; + for await (const chunk of stream) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); +} +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 \ No newline at end of file diff --git a/node_modules/agent-base/dist/helpers.js.map b/node_modules/agent-base/dist/helpers.js.map new file mode 100644 index 0000000..19df537 --- /dev/null +++ b/node_modules/agent-base/dist/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA6B;AAC7B,6CAA+B;AAOxB,KAAK,UAAU,QAAQ,CAAC,MAAgB;IAC9C,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,MAAM,EAAE;QACjC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC;QACvB,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;KACnB;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AACtC,CAAC;AARD,4BAQC;AAED,8DAA8D;AACvD,KAAK,UAAU,IAAI,CAAC,MAAgB;IAC1C,MAAM,GAAG,GAAG,MAAM,QAAQ,CAAC,MAAM,CAAC,CAAC;IACnC,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACjC,IAAI;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;KACvB;IAAC,OAAO,IAAa,EAAE;QACvB,MAAM,GAAG,GAAG,IAAa,CAAC;QAC1B,GAAG,CAAC,OAAO,IAAI,YAAY,GAAG,GAAG,CAAC;QAClC,MAAM,GAAG,CAAC;KACV;AACF,CAAC;AAVD,oBAUC;AAED,SAAgB,GAAG,CAClB,GAAiB,EACjB,OAA6B,EAAE;IAE/B,MAAM,IAAI,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC;IACtD,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,CAC7D,GAAG,EACH,IAAI,CACe,CAAC;IACrB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAuB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrE,GAAG;aACD,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC;aACzB,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC;aACrB,GAAG,EAAqB,CAAC;IAC5B,CAAC,CAAC,CAAC;IACH,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACtC,OAAO,GAAG,CAAC;AACZ,CAAC;AAjBD,kBAiBC"} \ No newline at end of file diff --git a/node_modules/agent-base/dist/index.d.ts b/node_modules/agent-base/dist/index.d.ts new file mode 100644 index 0000000..c849c34 --- /dev/null +++ b/node_modules/agent-base/dist/index.d.ts @@ -0,0 +1,41 @@ +/// +/// +/// +/// +import * as net from 'net'; +import * as tls from 'tls'; +import * as http from 'http'; +import type { Duplex } from 'stream'; +export * from './helpers'; +interface HttpConnectOpts extends net.TcpNetConnectOpts { + secureEndpoint: false; + protocol?: string; +} +interface HttpsConnectOpts extends tls.ConnectionOptions { + secureEndpoint: true; + protocol?: string; + port: number; +} +export type AgentConnectOpts = HttpConnectOpts | HttpsConnectOpts; +declare const INTERNAL: unique symbol; +export declare abstract class Agent extends http.Agent { + private [INTERNAL]; + options: Partial; + keepAlive: boolean; + constructor(opts?: http.AgentOptions); + abstract connect(req: http.ClientRequest, options: AgentConnectOpts): Promise | Duplex | http.Agent; + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options?: AgentConnectOpts): boolean; + private incrementSockets; + private decrementSockets; + getName(options: AgentConnectOpts): string; + createSocket(req: http.ClientRequest, options: AgentConnectOpts, cb: (err: Error | null, s?: Duplex) => void): void; + createConnection(): Duplex; + get defaultPort(): number; + set defaultPort(v: number); + get protocol(): string; + set protocol(v: string); +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/agent-base/dist/index.d.ts.map b/node_modules/agent-base/dist/index.d.ts.map new file mode 100644 index 0000000..25cdb5d --- /dev/null +++ b/node_modules/agent-base/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAAA,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,cAAc,WAAW,CAAC;AAE1B,UAAU,eAAgB,SAAQ,GAAG,CAAC,iBAAiB;IACtD,cAAc,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,UAAU,gBAAiB,SAAQ,GAAG,CAAC,iBAAiB;IACvD,cAAc,EAAE,IAAI,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,MAAM,gBAAgB,GAAG,eAAe,GAAG,gBAAgB,CAAC;AAElE,QAAA,MAAM,QAAQ,eAAmC,CAAC;AAQlD,8BAAsB,KAAM,SAAQ,IAAI,CAAC,KAAK;IAC7C,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAgB;IAGlC,OAAO,EAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,GAAG,GAAG,CAAC,iBAAiB,CAAC,CAAC;IACjE,SAAS,EAAG,OAAO,CAAC;gBAER,IAAI,CAAC,EAAE,IAAI,CAAC,YAAY;IAKpC,QAAQ,CAAC,OAAO,CACf,GAAG,EAAE,IAAI,CAAC,aAAa,EACvB,OAAO,EAAE,gBAAgB,GACvB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,MAAM,GAAG,IAAI,CAAC,KAAK;IAErD;;OAEG;IACH,gBAAgB,CAAC,OAAO,CAAC,EAAE,gBAAgB,GAAG,OAAO;IAqCrD,OAAO,CAAC,gBAAgB;IAqBxB,OAAO,CAAC,gBAAgB;IAmBxB,OAAO,CAAC,OAAO,EAAE,gBAAgB,GAAG,MAAM;IAa1C,YAAY,CACX,GAAG,EAAE,IAAI,CAAC,aAAa,EACvB,OAAO,EAAE,gBAAgB,EACzB,EAAE,EAAE,CAAC,GAAG,EAAE,KAAK,GAAG,IAAI,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,IAAI;IAgC5C,gBAAgB,IAAI,MAAM;IAW1B,IAAI,WAAW,IAAI,MAAM,CAKxB;IAED,IAAI,WAAW,CAAC,CAAC,EAAE,MAAM,EAIxB;IAED,IAAI,QAAQ,IAAI,MAAM,CAKrB;IAED,IAAI,QAAQ,CAAC,CAAC,EAAE,MAAM,EAIrB;CACD"} \ No newline at end of file diff --git a/node_modules/agent-base/dist/index.js b/node_modules/agent-base/dist/index.js new file mode 100644 index 0000000..c3c4099 --- /dev/null +++ b/node_modules/agent-base/dist/index.js @@ -0,0 +1,180 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __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(require("net")); +const http = __importStar(require("http")); +const https_1 = require("https"); +__exportStar(require("./helpers"), 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 = typeof options.secureEndpoint === 'boolean' + ? options.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 \ No newline at end of file diff --git a/node_modules/agent-base/dist/index.js.map b/node_modules/agent-base/dist/index.js.map new file mode 100644 index 0000000..d6e768c --- /dev/null +++ b/node_modules/agent-base/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAA2B;AAE3B,2CAA6B;AAC7B,iCAA4C;AAG5C,4CAA0B;AAe1B,MAAM,QAAQ,GAAG,MAAM,CAAC,wBAAwB,CAAC,CAAC;AAQlD,MAAsB,KAAM,SAAQ,IAAI,CAAC,KAAK;IAO7C,YAAY,IAAwB;QACnC,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC;IACrB,CAAC;IAOD;;OAEG;IACH,gBAAgB,CAAC,OAA0B;QAC1C,IAAI,OAAO,EA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I,KAAK,CACd,oDAAoD,CACpD,CAAC;SACF;QACD,OAAO,MAAM,CAAC;IACf,CAAC;IAED,IAAI,WAAW;QACd,OAAO,CACN,IAAI,CAAC,QAAQ,CAAC,CAAC,WAAW;YAC1B,CAAC,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CACvC,CAAC;IACH,CAAC;IAED,IAAI,WAAW,CAAC,CAAS;QACxB,IAAI,IAAI,CAAC,QAAQ,CAAC,EAAE;YACnB,IAAI,CAAC,QAAQ,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC;SAC/B;IACF,CAAC;IAED,IAAI,QAAQ;QACX,OAAO,CACN,IAAI,CAAC,QAAQ,CAAC,CAAC,QAAQ;YACvB,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAC9C,CAAC;IACH,CAAC;IAED,IAAI,QAAQ,CAAC,CAAS;QACrB,IAAI,IAAI,CAAC,QAAQ,CAAC,EAAE;YACnB,IAAI,CAAC,QAAQ,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC;SAC5B;IACF,CAAC;CACD;AArLD,sBAqLC"} \ No newline at end of file diff --git a/node_modules/agent-base/package.json b/node_modules/agent-base/package.json new file mode 100644 index 0000000..175ee71 --- /dev/null +++ b/node_modules/agent-base/package.json @@ -0,0 +1,46 @@ +{ + "name": "agent-base", + "version": "7.1.3", + "description": "Turn a function into an `http.Agent` instance", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "https://github.com/TooTallNate/proxy-agents.git", + "directory": "packages/agent-base" + }, + "keywords": [ + "http", + "agent", + "base", + "barebones", + "https" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "devDependencies": { + "@types/debug": "^4.1.7", + "@types/jest": "^29.5.1", + "@types/node": "^14.18.45", + "@types/semver": "^7.3.13", + "@types/ws": "^6.0.4", + "async-listen": "^3.0.0", + "jest": "^29.5.0", + "ts-jest": "^29.1.0", + "typescript": "^5.0.4", + "ws": "^5.2.4", + "tsconfig": "0.0.0" + }, + "engines": { + "node": ">= 14" + }, + "scripts": { + "build": "tsc", + "test": "jest --env node --verbose --bail", + "lint": "eslint . --ext .ts", + "pack": "node ../../scripts/pack.mjs" + } +} \ No newline at end of file diff --git a/node_modules/anymatch/LICENSE b/node_modules/anymatch/LICENSE new file mode 100644 index 0000000..491766c --- /dev/null +++ b/node_modules/anymatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" 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. diff --git a/node_modules/anymatch/README.md b/node_modules/anymatch/README.md new file mode 100644 index 0000000..1dd67f5 --- /dev/null +++ b/node_modules/anymatch/README.md @@ -0,0 +1,87 @@ +anymatch [![Build Status](https://travis-ci.org/micromatch/anymatch.svg?branch=master)](https://travis-ci.org/micromatch/anymatch) [![Coverage Status](https://img.shields.io/coveralls/micromatch/anymatch.svg?branch=master)](https://coveralls.io/r/micromatch/anymatch?branch=master) +====== +Javascript module to match a string against a regular expression, glob, string, +or function that takes the string as an argument and returns a truthy or falsy +value. The matcher can also be an array of any or all of these. Useful for +allowing a very flexible user-defined config to define things like file paths. + +__Note: This module has Bash-parity, please be aware that Windows-style backslashes are not supported as separators. See https://github.com/micromatch/micromatch#backslashes for more information.__ + + +Usage +----- +```sh +npm install anymatch +``` + +#### anymatch(matchers, testString, [returnIndex], [options]) +* __matchers__: (_Array|String|RegExp|Function_) +String to be directly matched, string with glob patterns, regular expression +test, function that takes the testString as an argument and returns a truthy +value if it should be matched, or an array of any number and mix of these types. +* __testString__: (_String|Array_) The string to test against the matchers. If +passed as an array, the first element of the array will be used as the +`testString` for non-function matchers, while the entire array will be applied +as the arguments for function matchers. +* __options__: (_Object_ [optional]_) Any of the [picomatch](https://github.com/micromatch/picomatch#options) options. + * __returnIndex__: (_Boolean [optional]_) If true, return the array index of +the first matcher that that testString matched, or -1 if no match, instead of a +boolean result. + +```js +const anymatch = require('anymatch'); + +const matchers = [ 'path/to/file.js', 'path/anyjs/**/*.js', /foo.js$/, string => string.includes('bar') && string.length > 10 ] ; + +anymatch(matchers, 'path/to/file.js'); // true +anymatch(matchers, 'path/anyjs/baz.js'); // true +anymatch(matchers, 'path/to/foo.js'); // true +anymatch(matchers, 'path/to/bar.js'); // true +anymatch(matchers, 'bar.js'); // false + +// returnIndex = true +anymatch(matchers, 'foo.js', {returnIndex: true}); // 2 +anymatch(matchers, 'path/anyjs/foo.js', {returnIndex: true}); // 1 + +// any picomatc + +// using globs to match directories and their children +anymatch('node_modules', 'node_modules'); // true +anymatch('node_modules', 'node_modules/somelib/index.js'); // false +anymatch('node_modules/**', 'node_modules/somelib/index.js'); // true +anymatch('node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // false +anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // true + +const matcher = anymatch(matchers); +['foo.js', 'bar.js'].filter(matcher); // [ 'foo.js' ] +anymatch master* ❯ + +``` + +#### anymatch(matchers) +You can also pass in only your matcher(s) to get a curried function that has +already been bound to the provided matching criteria. This can be used as an +`Array#filter` callback. + +```js +var matcher = anymatch(matchers); + +matcher('path/to/file.js'); // true +matcher('path/anyjs/baz.js', true); // 1 + +['foo.js', 'bar.js'].filter(matcher); // ['foo.js'] +``` + +Changelog +---------- +[See release notes page on GitHub](https://github.com/micromatch/anymatch/releases) + +- **v3.0:** Removed `startIndex` and `endIndex` arguments. Node 8.x-only. +- **v2.0:** [micromatch](https://github.com/jonschlinkert/micromatch) moves away from minimatch-parity and inline with Bash. This includes handling backslashes differently (see https://github.com/micromatch/micromatch#backslashes for more information). +- **v1.2:** anymatch uses [micromatch](https://github.com/jonschlinkert/micromatch) +for glob pattern matching. Issues with glob pattern matching should be +reported directly to the [micromatch issue tracker](https://github.com/jonschlinkert/micromatch/issues). + +License +------- +[ISC](https://raw.github.com/micromatch/anymatch/master/LICENSE) diff --git a/node_modules/anymatch/index.d.ts b/node_modules/anymatch/index.d.ts new file mode 100644 index 0000000..3ef7eaa --- /dev/null +++ b/node_modules/anymatch/index.d.ts @@ -0,0 +1,20 @@ +type AnymatchFn = (testString: string) => boolean; +type AnymatchPattern = string|RegExp|AnymatchFn; +type AnymatchMatcher = AnymatchPattern|AnymatchPattern[] +type AnymatchTester = { + (testString: string|any[], returnIndex: true): number; + (testString: string|any[]): boolean; +} + +type PicomatchOptions = {dot: boolean}; + +declare const anymatch: { + (matchers: AnymatchMatcher): AnymatchTester; + (matchers: AnymatchMatcher, testString: null, returnIndex: true | PicomatchOptions): AnymatchTester; + (matchers: AnymatchMatcher, testString: string|any[], returnIndex: true | PicomatchOptions): number; + (matchers: AnymatchMatcher, testString: string|any[]): boolean; +} + +export {AnymatchMatcher as Matcher} +export {AnymatchTester as Tester} +export default anymatch diff --git a/node_modules/anymatch/index.js b/node_modules/anymatch/index.js new file mode 100644 index 0000000..8eb73e9 --- /dev/null +++ b/node_modules/anymatch/index.js @@ -0,0 +1,104 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { value: true }); + +const picomatch = require('picomatch'); +const normalizePath = require('normalize-path'); + +/** + * @typedef {(testString: string) => boolean} AnymatchFn + * @typedef {string|RegExp|AnymatchFn} AnymatchPattern + * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher + */ +const BANG = '!'; +const DEFAULT_OPTIONS = {returnIndex: false}; +const arrify = (item) => Array.isArray(item) ? item : [item]; + +/** + * @param {AnymatchPattern} matcher + * @param {object} options + * @returns {AnymatchFn} + */ +const createPattern = (matcher, options) => { + if (typeof matcher === 'function') { + return matcher; + } + if (typeof matcher === 'string') { + const glob = picomatch(matcher, options); + return (string) => matcher === string || glob(string); + } + if (matcher instanceof RegExp) { + return (string) => matcher.test(string); + } + return (string) => false; +}; + +/** + * @param {Array} patterns + * @param {Array} negPatterns + * @param {String|Array} args + * @param {Boolean} returnIndex + * @returns {boolean|number} + */ +const matchPatterns = (patterns, negPatterns, args, returnIndex) => { + const isList = Array.isArray(args); + const _path = isList ? args[0] : args; + if (!isList && typeof _path !== 'string') { + throw new TypeError('anymatch: second argument must be a string: got ' + + Object.prototype.toString.call(_path)) + } + const path = normalizePath(_path, false); + + for (let index = 0; index < negPatterns.length; index++) { + const nglob = negPatterns[index]; + if (nglob(path)) { + return returnIndex ? -1 : false; + } + } + + const applied = isList && [path].concat(args.slice(1)); + for (let index = 0; index < patterns.length; index++) { + const pattern = patterns[index]; + if (isList ? pattern(...applied) : pattern(path)) { + return returnIndex ? index : true; + } + } + + return returnIndex ? -1 : false; +}; + +/** + * @param {AnymatchMatcher} matchers + * @param {Array|string} testString + * @param {object} options + * @returns {boolean|number|Function} + */ +const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => { + if (matchers == null) { + throw new TypeError('anymatch: specify first argument'); + } + const opts = typeof options === 'boolean' ? {returnIndex: options} : options; + const returnIndex = opts.returnIndex || false; + + // Early cache for matchers. + const mtchers = arrify(matchers); + const negatedGlobs = mtchers + .filter(item => typeof item === 'string' && item.charAt(0) === BANG) + .map(item => item.slice(1)) + .map(item => picomatch(item, opts)); + const patterns = mtchers + .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG)) + .map(matcher => createPattern(matcher, opts)); + + if (testString == null) { + return (testString, ri = false) => { + const returnIndex = typeof ri === 'boolean' ? ri : false; + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); + } + } + + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); +}; + +anymatch.default = anymatch; +module.exports = anymatch; diff --git a/node_modules/anymatch/package.json b/node_modules/anymatch/package.json new file mode 100644 index 0000000..2cb2307 --- /dev/null +++ b/node_modules/anymatch/package.json @@ -0,0 +1,48 @@ +{ + "name": "anymatch", + "version": "3.1.3", + "description": "Matches strings against configurable strings, globs, regular expressions, and/or functions", + "files": [ + "index.js", + "index.d.ts" + ], + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "author": { + "name": "Elan Shanker", + "url": "https://github.com/es128" + }, + "license": "ISC", + "homepage": "https://github.com/micromatch/anymatch", + "repository": { + "type": "git", + "url": "https://github.com/micromatch/anymatch" + }, + "keywords": [ + "match", + "any", + "string", + "file", + "fs", + "list", + "glob", + "regex", + "regexp", + "regular", + "expression", + "function" + ], + "scripts": { + "test": "nyc mocha", + "mocha": "mocha" + }, + "devDependencies": { + "mocha": "^6.1.3", + "nyc": "^14.0.0" + }, + "engines": { + "node": ">= 8" + } +} diff --git a/node_modules/array-flatten/LICENSE b/node_modules/array-flatten/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/node_modules/array-flatten/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/array-flatten/README.md b/node_modules/array-flatten/README.md new file mode 100644 index 0000000..91fa5b6 --- /dev/null +++ b/node_modules/array-flatten/README.md @@ -0,0 +1,43 @@ +# Array Flatten + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +> Flatten an array of nested arrays into a single flat array. Accepts an optional depth. + +## Installation + +``` +npm install array-flatten --save +``` + +## Usage + +```javascript +var flatten = require('array-flatten') + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) +//=> [1, 2, 3, 4, 5, 6, 7, 8, 9] + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) +//=> [1, 2, 3, [4, [5], 6], 7, 8, 9] + +(function () { + flatten(arguments) //=> [1, 2, 3] +})(1, [2, 3]) +``` + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat +[npm-url]: https://npmjs.org/package/array-flatten +[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat +[downloads-url]: https://npmjs.org/package/array-flatten +[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat +[travis-url]: https://travis-ci.org/blakeembrey/array-flatten +[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat +[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master diff --git a/node_modules/array-flatten/array-flatten.js b/node_modules/array-flatten/array-flatten.js new file mode 100644 index 0000000..089117b --- /dev/null +++ b/node_modules/array-flatten/array-flatten.js @@ -0,0 +1,64 @@ +'use strict' + +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten + +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } + + return result +} + +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } + + return result +} + +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) +} diff --git a/node_modules/array-flatten/package.json b/node_modules/array-flatten/package.json new file mode 100644 index 0000000..1a24e2a --- /dev/null +++ b/node_modules/array-flatten/package.json @@ -0,0 +1,39 @@ +{ + "name": "array-flatten", + "version": "1.1.1", + "description": "Flatten an array of nested arrays into a single flat array", + "main": "array-flatten.js", + "files": [ + "array-flatten.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/blakeembrey/array-flatten.git" + }, + "keywords": [ + "array", + "flatten", + "arguments", + "depth" + ], + "author": { + "name": "Blake Embrey", + "email": "hello@blakeembrey.com", + "url": "http://blakeembrey.me" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/blakeembrey/array-flatten/issues" + }, + "homepage": "https://github.com/blakeembrey/array-flatten", + "devDependencies": { + "istanbul": "^0.3.13", + "mocha": "^2.2.4", + "pre-commit": "^1.0.7", + "standard": "^3.7.3" + } +} diff --git a/node_modules/balanced-match/.github/FUNDING.yml b/node_modules/balanced-match/.github/FUNDING.yml new file mode 100644 index 0000000..cea8b16 --- /dev/null +++ b/node_modules/balanced-match/.github/FUNDING.yml @@ -0,0 +1,2 @@ +tidelift: "npm/balanced-match" +patreon: juliangruber diff --git a/node_modules/balanced-match/LICENSE.md b/node_modules/balanced-match/LICENSE.md new file mode 100644 index 0000000..2cdc8e4 --- /dev/null +++ b/node_modules/balanced-match/LICENSE.md @@ -0,0 +1,21 @@ +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/README.md b/node_modules/balanced-match/README.md new file mode 100644 index 0000000..d2a48b6 --- /dev/null +++ b/node_modules/balanced-match/README.md @@ -0,0 +1,97 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### var r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/index.js b/node_modules/balanced-match/index.js new file mode 100644 index 0000000..c67a646 --- /dev/null +++ b/node_modules/balanced-match/index.js @@ -0,0 +1,62 @@ +'use strict'; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} diff --git a/node_modules/balanced-match/package.json b/node_modules/balanced-match/package.json new file mode 100644 index 0000000..ce6073e --- /dev/null +++ b/node_modules/balanced-match/package.json @@ -0,0 +1,48 @@ +{ + "name": "balanced-match", + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "version": "1.0.2", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "main": "index.js", + "scripts": { + "test": "tape test/test.js", + "bench": "matcha test/bench.js" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/base64-js/LICENSE b/node_modules/base64-js/LICENSE new file mode 100644 index 0000000..6d52b8a --- /dev/null +++ b/node_modules/base64-js/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jameson Little + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/base64-js/README.md b/node_modules/base64-js/README.md new file mode 100644 index 0000000..b42a48f --- /dev/null +++ b/node_modules/base64-js/README.md @@ -0,0 +1,34 @@ +base64-js +========= + +`base64-js` does basic base64 encoding/decoding in pure JS. + +[![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js) + +Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data. + +Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does. + +## install + +With [npm](https://npmjs.org) do: + +`npm install base64-js` and `var base64js = require('base64-js')` + +For use in web browsers do: + +`` + +[Get supported base64-js with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-base64-js?utm_source=npm-base64-js&utm_medium=referral&utm_campaign=readme) + +## methods + +`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. + +* `byteLength` - Takes a base64 string and returns length of byte array +* `toByteArray` - Takes a base64 string and returns a byte array +* `fromByteArray` - Takes a byte array and returns a base64 string + +## license + +MIT diff --git a/node_modules/base64-js/base64js.min.js b/node_modules/base64-js/base64js.min.js new file mode 100644 index 0000000..908ac83 --- /dev/null +++ b/node_modules/base64-js/base64js.min.js @@ -0,0 +1 @@ +(function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,b.base64js=a()}})(function(){return function(){function b(d,e,g){function a(j,i){if(!e[j]){if(!d[j]){var f="function"==typeof require&&require;if(!i&&f)return f(j,!0);if(h)return h(j,!0);var c=new Error("Cannot find module '"+j+"'");throw c.code="MODULE_NOT_FOUND",c}var k=e[j]={exports:{}};d[j][0].call(k.exports,function(b){var c=d[j][1][b];return a(c||b)},k,k.exports,b,d,e,g)}return e[j].exports}for(var h="function"==typeof require&&require,c=0;c>16,j[k++]=255&b>>8,j[k++]=255&b;return 2===h&&(b=l[a.charCodeAt(c)]<<2|l[a.charCodeAt(c+1)]>>4,j[k++]=255&b),1===h&&(b=l[a.charCodeAt(c)]<<10|l[a.charCodeAt(c+1)]<<4|l[a.charCodeAt(c+2)]>>2,j[k++]=255&b>>8,j[k++]=255&b),j}function g(a){return k[63&a>>18]+k[63&a>>12]+k[63&a>>6]+k[63&a]}function h(a,b,c){for(var d,e=[],f=b;fj?j:g+f));return 1===d?(b=a[c-1],e.push(k[b>>2]+k[63&b<<4]+"==")):2===d&&(b=(a[c-2]<<8)+a[c-1],e.push(k[b>>10]+k[63&b>>4]+k[63&b<<2]+"=")),e.join("")}c.byteLength=function(a){var b=d(a),c=b[0],e=b[1];return 3*(c+e)/4-e},c.toByteArray=f,c.fromByteArray=j;for(var k=[],l=[],m="undefined"==typeof Uint8Array?Array:Uint8Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,p=n.length;o 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('') +} diff --git a/node_modules/base64-js/package.json b/node_modules/base64-js/package.json new file mode 100644 index 0000000..c3972e3 --- /dev/null +++ b/node_modules/base64-js/package.json @@ -0,0 +1,47 @@ +{ + "name": "base64-js", + "description": "Base64 encoding/decoding in pure JS", + "version": "1.5.1", + "author": "T. Jameson Little ", + "typings": "index.d.ts", + "bugs": { + "url": "https://github.com/beatgammit/base64-js/issues" + }, + "devDependencies": { + "babel-minify": "^0.5.1", + "benchmark": "^2.1.4", + "browserify": "^16.3.0", + "standard": "*", + "tape": "4.x" + }, + "homepage": "https://github.com/beatgammit/base64-js", + "keywords": [ + "base64" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/beatgammit/base64-js.git" + }, + "scripts": { + "build": "browserify -s base64js -r ./ | minify > base64js.min.js", + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/bignumber.js/CHANGELOG.md b/node_modules/bignumber.js/CHANGELOG.md new file mode 100644 index 0000000..9586720 --- /dev/null +++ b/node_modules/bignumber.js/CHANGELOG.md @@ -0,0 +1,295 @@ +#### 9.1.2 +* 28/08/23 +* #354 Amend `round` to avoid bug in v8 Maglev compiler. +* [BUGFIX] #344 `minumum(0, -0)` should be `-0`. + +#### 9.1.1 +* 04/12/22 +* #338 [BUGFIX] `exponentiatedBy`: ensure `0**-n === Infinity` for very large `n`. + +#### 9.1.0 +* 08/08/22 +* #329 Remove `import` example. +* #277 Resolve lint warnings and add number `toString` note. +* Correct `decimalPlaces()` return type in *bignumber.d.ts*. +* Add ES module global `crypto` example. +* #322 Add `exports` field to *package.json*. +* #251 (#308) Amend *bignumber.d.ts* to allow instantiating a BigNumber without `new`. + +#### 9.0.2 +* 12/12/21 +* #250 [BUGFIX] Allow use of user-defined alphabet for base 10. +* #295 Remove *bignumber.min.js* and amend *README.md*. +* Update *.travis.yml* and *LICENCE.md*. + +#### 9.0.1 +* 28/09/20 +* [BUGFIX] #276 Correct `sqrt` initial estimate. +* Update *.travis.yml*, *LICENCE.md* and *README.md*. + +#### 9.0.0 +* 27/05/2019 +* For compatibility with legacy browsers, remove `Symbol` references. + +#### 8.1.1 +* 24/02/2019 +* [BUGFIX] #222 Restore missing `var` to `export BigNumber`. +* Allow any key in BigNumber.Instance in *bignumber.d.ts*. + +#### 8.1.0 +* 23/02/2019 +* [NEW FEATURE] #220 Create a BigNumber using `{s, e, c}`. +* [NEW FEATURE] `isBigNumber`: if `BigNumber.DEBUG` is `true`, also check that the BigNumber instance is well-formed. +* Remove `instanceof` checks; just use `_isBigNumber` to identify a BigNumber instance. +* Add `_isBigNumber` to prototype in *bignumber.mjs*. +* Add tests for BigNumber creation from object. +* Update *API.html*. + +#### 8.0.2 +* 13/01/2019 +* #209 `toPrecision` without argument should follow `toString`. +* Improve *Use* section of *README*. +* Optimise `toString(10)`. +* Add verson number to API doc. + +#### 8.0.1 +* 01/11/2018 +* Rest parameter must be array type in *bignumber.d.ts*. + +#### 8.0.0 +* 01/11/2018 +* [NEW FEATURE] Add `BigNumber.sum` method. +* [NEW FEATURE]`toFormat`: add `prefix` and `suffix` options. +* [NEW FEATURE] #178 Pass custom formatting to `toFormat`. +* [BREAKING CHANGE] #184 `toFraction`: return array of BigNumbers not strings. +* [NEW FEATURE] #185 Enable overwrite of `valueOf` to prevent accidental addition to string. +* #183 Add Node.js `crypto` requirement to documentation. +* [BREAKING CHANGE] #198 Disallow signs and whitespace in custom alphabet. +* [NEW FEATURE] #188 Implement `util.inspect.custom` for Node.js REPL. +* #170 Make `isBigNumber` a type guard in *bignumber.d.ts*. +* [BREAKING CHANGE] `BigNumber.min` and `BigNumber.max`: don't accept an array. +* Update *.travis.yml*. +* Remove *bower.json*. + +#### 7.2.1 +* 24/05/2018 +* Add `browser` field to *package.json*. + +#### 7.2.0 +* 22/05/2018 +* #166 Correct *.mjs* file. Remove extension from `main` field in *package.json*. + +#### 7.1.0 +* 18/05/2018 +* Add `module` field to *package.json* for *bignumber.mjs*. + +#### 7.0.2 +* 17/05/2018 +* #165 Bugfix: upper-case letters for bases 11-36 in a custom alphabet. +* Add note to *README* regarding creating BigNumbers from Number values. + +#### 7.0.1 +* 26/04/2018 +* #158 Fix global object variable name typo. + +#### 7.0.0 +* 26/04/2018 +* #143 Remove global BigNumber from typings. +* #144 Enable compatibility with `Object.freeze(Object.prototype)`. +* #148 #123 #11 Only throw on a number primitive with more than 15 significant digits if `BigNumber.DEBUG` is `true`. +* Only throw on an invalid BigNumber value if `BigNumber.DEBUG` is `true`. Return BigNumber `NaN` instead. +* #154 `exponentiatedBy`: allow BigNumber exponent. +* #156 Prevent Content Security Policy *unsafe-eval* issue. +* `toFraction`: allow `Infinity` maximum denominator. +* Comment-out some excess tests to reduce test time. +* Amend indentation and other spacing. + +#### 6.0.0 +* 26/01/2018 +* #137 Implement `APLHABET` configuration option. +* Remove `ERRORS` configuration option. +* Remove `toDigits` method; extend `precision` method accordingly. +* Remove s`round` method; extend `decimalPlaces` method accordingly. +* Remove methods: `ceil`, `floor`, and `truncated`. +* Remove method aliases: `add`, `cmp`, `isInt`, `isNeg`, `trunc`, `mul`, `neg` and `sub`. +* Rename methods: `shift` to `shiftedBy`, `another` to `clone`, `toPower` to `exponentiatedBy`, and `equals` to `isEqualTo`. +* Rename methods: add `is` prefix to `greaterThan`, `greaterThanOrEqualTo`, `lessThan` and `lessThanOrEqualTo`. +* Add methods: `multipliedBy`, `isBigNumber`, `isPositive`, `integerValue`, `maximum` and `minimum`. +* Refactor test suite. +* Add *CHANGELOG.md*. +* Rewrite *bignumber.d.ts*. +* Redo API image. + +#### 5.0.0 +* 27/11/2017 +* #81 Don't throw on constructor call without `new`. + +#### 4.1.0 +* 26/09/2017 +* Remove node 0.6 from *.travis.yml*. +* Add *bignumber.mjs*. + +#### 4.0.4 +* 03/09/2017 +* Add missing aliases to *bignumber.d.ts*. + +#### 4.0.3 +* 30/08/2017 +* Add types: *bignumber.d.ts*. + +#### 4.0.2 +* 03/05/2017 +* #120 Workaround Safari/Webkit bug. + +#### 4.0.1 +* 05/04/2017 +* #121 BigNumber.default to BigNumber['default']. + +#### 4.0.0 +* 09/01/2017 +* Replace BigNumber.isBigNumber method with isBigNumber prototype property. + +#### 3.1.2 +* 08/01/2017 +* Minor documentation edit. + +#### 3.1.1 +* 08/01/2017 +* Uncomment `isBigNumber` tests. +* Ignore dot files. + +#### 3.1.0 +* 08/01/2017 +* Add `isBigNumber` method. + +#### 3.0.2 +* 08/01/2017 +* Bugfix: Possible incorrect value of `ERRORS` after a `BigNumber.another` call (due to `parseNumeric` declaration in outer scope). + +#### 3.0.1 +* 23/11/2016 +* Apply fix for old ipads with `%` issue, see #57 and #102. +* Correct error message. + +#### 3.0.0 +* 09/11/2016 +* Remove `require('crypto')` - leave it to the user. +* Add `BigNumber.set` as `BigNumber.config` alias. +* Default `POW_PRECISION` to `0`. + +#### 2.4.0 +* 14/07/2016 +* #97 Add exports to support ES6 imports. + +#### 2.3.0 +* 07/03/2016 +* #86 Add modulus parameter to `toPower`. + +#### 2.2.0 +* 03/03/2016 +* #91 Permit larger JS integers. + +#### 2.1.4 +* 15/12/2015 +* Correct UMD. + +#### 2.1.3 +* 13/12/2015 +* Refactor re global object and crypto availability when bundling. + +#### 2.1.2 +* 10/12/2015 +* Bugfix: `window.crypto` not assigned to `crypto`. + +#### 2.1.1 +* 09/12/2015 +* Prevent code bundler from adding `crypto` shim. + +#### 2.1.0 +* 26/10/2015 +* For `valueOf` and `toJSON`, include the minus sign with negative zero. + +#### 2.0.8 +* 2/10/2015 +* Internal round function bugfix. + +#### 2.0.6 +* 31/03/2015 +* Add bower.json. Tweak division after in-depth review. + +#### 2.0.5 +* 25/03/2015 +* Amend README. Remove bitcoin address. + +#### 2.0.4 +* 25/03/2015 +* Critical bugfix #58: division. + +#### 2.0.3 +* 18/02/2015 +* Amend README. Add source map. + +#### 2.0.2 +* 18/02/2015 +* Correct links. + +#### 2.0.1 +* 18/02/2015 +* Add `max`, `min`, `precision`, `random`, `shiftedBy`, `toDigits` and `truncated` methods. +* Add the short-forms: `add`, `mul`, `sd`, `sub` and `trunc`. +* Add an `another` method to enable multiple independent constructors to be created. +* Add support for the base 2, 8 and 16 prefixes `0b`, `0o` and `0x`. +* Enable a rounding mode to be specified as a second parameter to `toExponential`, `toFixed`, `toFormat` and `toPrecision`. +* Add a `CRYPTO` configuration property so cryptographically-secure pseudo-random number generation can be specified. +* Add a `MODULO_MODE` configuration property to enable the rounding mode used by the `modulo` operation to be specified. +* Add a `POW_PRECISION` configuration property to enable the number of significant digits calculated by the power operation to be limited. +* Improve code quality. +* Improve documentation. + +#### 2.0.0 +* 29/12/2014 +* Add `dividedToIntegerBy`, `isInteger` and `toFormat` methods. +* Remove the following short-forms: `isF`, `isZ`, `toE`, `toF`, `toFr`, `toN`, `toP`, `toS`. +* Store a BigNumber's coefficient in base 1e14, rather than base 10. +* Add fast path for integers to BigNumber constructor. +* Incorporate the library into the online documentation. + +#### 1.5.0 +* 13/11/2014 +* Add `toJSON` and `decimalPlaces` methods. + +#### 1.4.1 +* 08/06/2014 +* Amend README. + +#### 1.4.0 +* 08/05/2014 +* Add `toNumber`. + +#### 1.3.0 +* 08/11/2013 +* Ensure correct rounding of `sqrt` in all, rather than almost all, cases. +* Maximum radix to 64. + +#### 1.2.1 +* 17/10/2013 +* Sign of zero when x < 0 and x + (-x) = 0. + +#### 1.2.0 +* 19/9/2013 +* Throw Error objects for stack. + +#### 1.1.1 +* 22/8/2013 +* Show original value in constructor error message. + +#### 1.1.0 +* 1/8/2013 +* Allow numbers with trailing radix point. + +#### 1.0.1 +* Bugfix: error messages with incorrect method name + +#### 1.0.0 +* 8/11/2012 +* Initial release diff --git a/node_modules/bignumber.js/LICENCE.md b/node_modules/bignumber.js/LICENCE.md new file mode 100644 index 0000000..3c2f6a3 --- /dev/null +++ b/node_modules/bignumber.js/LICENCE.md @@ -0,0 +1,26 @@ +The MIT License (MIT) +===================== + +Copyright © `<2023>` `Michael Mclaughlin` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/bignumber.js/README.md b/node_modules/bignumber.js/README.md new file mode 100644 index 0000000..4785443 --- /dev/null +++ b/node_modules/bignumber.js/README.md @@ -0,0 +1,286 @@ +![bignumber.js](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/bignumberjs.png) + +A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic. + +[![npm version](https://img.shields.io/npm/v/bignumber.js.svg)](https://www.npmjs.com/package/bignumber.js) +[![npm downloads](https://img.shields.io/npm/dw/bignumber.js)](https://www.npmjs.com/package/bignumber.js) + +
+ +## Features + +- Integers and decimals +- Simple API but full-featured +- Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal +- 8 KB minified and gzipped +- Replicates the `toExponential`, `toFixed`, `toPrecision` and `toString` methods of JavaScript's Number type +- Includes a `toFraction` and a correctly-rounded `squareRoot` method +- Supports cryptographically-secure pseudo-random number generation +- No dependencies +- Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only +- Comprehensive [documentation](http://mikemcl.github.io/bignumber.js/) and test set + +![API](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/API.png) + +If a smaller and simpler library is required see [big.js](https://github.com/MikeMcl/big.js/). +It's less than half the size but only works with decimal numbers and only has half the methods. +It also has fewer configuration options than this library, and does not allow `NaN` or `Infinity`. + +See also [decimal.js](https://github.com/MikeMcl/decimal.js/), which among other things adds support for non-integer powers, and performs all operations to a specified number of significant digits. + +## Load + +The library is the single JavaScript file *bignumber.js* or ES module *bignumber.mjs*. + +### Browser + +```html + +``` + +> ES module + +```html + +``` + +### [Node.js](http://nodejs.org) + +```bash +npm install bignumber.js +``` + +```javascript +const BigNumber = require('bignumber.js'); +``` + +> ES module + +```javascript +import BigNumber from "bignumber.js"; +import { BigNumber } from "./node_modules/bignumber.js/bignumber.mjs"; +``` + +### [Deno](https://deno.land/) + +```javascript +import BigNumber from 'https://raw.githubusercontent.com/mikemcl/bignumber.js/v9.1.2/bignumber.mjs'; +import BigNumber from 'https://unpkg.com/bignumber.js@latest/bignumber.mjs'; +``` + +## Use + +The library exports a single constructor function, [`BigNumber`](http://mikemcl.github.io/bignumber.js/#bignumber), which accepts a value of type Number, String or BigNumber, + +```javascript +let x = new BigNumber(123.4567); +let y = BigNumber('123456.7e-3'); +let z = new BigNumber(x); +x.isEqualTo(y) && y.isEqualTo(z) && x.isEqualTo(z); // true +``` + +To get the string value of a BigNumber use [`toString()`](http://mikemcl.github.io/bignumber.js/#toS) or [`toFixed()`](http://mikemcl.github.io/bignumber.js/#toFix). Using `toFixed()` prevents exponential notation being returned, no matter how large or small the value. + +```javascript +let x = new BigNumber('1111222233334444555566'); +x.toString(); // "1.111222233334444555566e+21" +x.toFixed(); // "1111222233334444555566" +``` + +If the limited precision of Number values is not well understood, it is recommended to create BigNumbers from String values rather than Number values to avoid a potential loss of precision. + +*In all further examples below, `let`, semicolons and `toString` calls are not shown. If a commented-out value is in quotes it means `toString` has been called on the preceding expression.* + +```javascript +// Precision loss from using numeric literals with more than 15 significant digits. +new BigNumber(1.0000000000000001) // '1' +new BigNumber(88259496234518.57) // '88259496234518.56' +new BigNumber(99999999999999999999) // '100000000000000000000' + +// Precision loss from using numeric literals outside the range of Number values. +new BigNumber(2e+308) // 'Infinity' +new BigNumber(1e-324) // '0' + +// Precision loss from the unexpected result of arithmetic with Number values. +new BigNumber(0.7 + 0.1) // '0.7999999999999999' +``` + +When creating a BigNumber from a Number, note that a BigNumber is created from a Number's decimal `toString()` value not from its underlying binary value. If the latter is required, then pass the Number's `toString(2)` value and specify base 2. + +```javascript +new BigNumber(Number.MAX_VALUE.toString(2), 2) +``` + +BigNumbers can be created from values in bases from 2 to 36. See [`ALPHABET`](http://mikemcl.github.io/bignumber.js/#alphabet) to extend this range. + +```javascript +a = new BigNumber(1011, 2) // "11" +b = new BigNumber('zz.9', 36) // "1295.25" +c = a.plus(b) // "1306.25" +``` + +*Performance is better if base 10 is NOT specified for decimal values. Only specify base 10 when you want to limit the number of decimal places of the input value to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.* + +A BigNumber is immutable in the sense that it is not changed by its methods. + +```javascript +0.3 - 0.1 // 0.19999999999999998 +x = new BigNumber(0.3) +x.minus(0.1) // "0.2" +x // "0.3" +``` + +The methods that return a BigNumber can be chained. + +```javascript +x.dividedBy(y).plus(z).times(9) +x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').integerValue() +``` + +Some of the longer method names have a shorter alias. + +```javascript +x.squareRoot().dividedBy(y).exponentiatedBy(3).isEqualTo(x.sqrt().div(y).pow(3)) // true +x.modulo(y).multipliedBy(z).eq(x.mod(y).times(z)) // true +``` + +As with JavaScript's Number type, there are [`toExponential`](http://mikemcl.github.io/bignumber.js/#toE), [`toFixed`](http://mikemcl.github.io/bignumber.js/#toFix) and [`toPrecision`](http://mikemcl.github.io/bignumber.js/#toP) methods. + +```javascript +x = new BigNumber(255.5) +x.toExponential(5) // "2.55500e+2" +x.toFixed(5) // "255.50000" +x.toPrecision(5) // "255.50" +x.toNumber() // 255.5 +``` + + A base can be specified for [`toString`](http://mikemcl.github.io/bignumber.js/#toS). + +*Performance is better if base 10 is NOT specified, i.e. use `toString()` not `toString(10)`. Only specify base 10 when you want to limit the number of decimal places of the string to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.* + + ```javascript + x.toString(16) // "ff.8" + ``` + +There is a [`toFormat`](http://mikemcl.github.io/bignumber.js/#toFor) method which may be useful for internationalisation. + +```javascript +y = new BigNumber('1234567.898765') +y.toFormat(2) // "1,234,567.90" +``` + +The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the `set` or `config` method of the `BigNumber` constructor. + +The other arithmetic operations always give the exact result. + +```javascript +BigNumber.set({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 }) + +x = new BigNumber(2) +y = new BigNumber(3) +z = x.dividedBy(y) // "0.6666666667" +z.squareRoot() // "0.8164965809" +z.exponentiatedBy(-3) // "3.3749999995" +z.toString(2) // "0.1010101011" +z.multipliedBy(z) // "0.44444444448888888889" +z.multipliedBy(z).decimalPlaces(10) // "0.4444444445" +``` + +There is a [`toFraction`](http://mikemcl.github.io/bignumber.js/#toFr) method with an optional *maximum denominator* argument + +```javascript +y = new BigNumber(355) +pi = y.dividedBy(113) // "3.1415929204" +pi.toFraction() // [ "7853982301", "2500000000" ] +pi.toFraction(1000) // [ "355", "113" ] +``` + +and [`isNaN`](http://mikemcl.github.io/bignumber.js/#isNaN) and [`isFinite`](http://mikemcl.github.io/bignumber.js/#isF) methods, as `NaN` and `Infinity` are valid `BigNumber` values. + +```javascript +x = new BigNumber(NaN) // "NaN" +y = new BigNumber(Infinity) // "Infinity" +x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true +``` + +The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign. + +```javascript +x = new BigNumber(-123.456); +x.c // [ 123, 45600000000000 ] coefficient (i.e. significand) +x.e // 2 exponent +x.s // -1 sign +``` + +For advanced usage, multiple BigNumber constructors can be created, each with its own independent configuration. + +```javascript +// Set DECIMAL_PLACES for the original BigNumber constructor +BigNumber.set({ DECIMAL_PLACES: 10 }) + +// Create another BigNumber constructor, optionally passing in a configuration object +BN = BigNumber.clone({ DECIMAL_PLACES: 5 }) + +x = new BigNumber(1) +y = new BN(1) + +x.div(3) // '0.3333333333' +y.div(3) // '0.33333' +``` + +To avoid having to call `toString` or `valueOf` on a BigNumber to get its value in the Node.js REPL or when using `console.log` use + +```javascript +BigNumber.prototype[require('util').inspect.custom] = BigNumber.prototype.valueOf; +``` + +For further information see the [API](http://mikemcl.github.io/bignumber.js/) reference in the *doc* directory. + +## Test + +The *test/modules* directory contains the test scripts for each method. + +The tests can be run with Node.js or a browser. For Node.js use + +```bash +npm test +``` + +or + +```bash +node test/test +``` + +To test a single method, use, for example + +```bash +node test/methods/toFraction +``` + +For the browser, open *test/test.html*. + +## Minify + +To minify using, for example, [terser](https://github.com/terser/terser) + +```bash +npm install -g terser +``` + +```bash +terser big.js -c -m -o big.min.js +``` + +## Licence + +The MIT Licence. + +See [LICENCE](https://github.com/MikeMcl/bignumber.js/blob/master/LICENCE). diff --git a/node_modules/bignumber.js/bignumber.d.ts b/node_modules/bignumber.js/bignumber.d.ts new file mode 100644 index 0000000..c5a60a8 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.d.ts @@ -0,0 +1,1831 @@ +// Type definitions for bignumber.js >=8.1.0 +// Project: https://github.com/MikeMcl/bignumber.js +// Definitions by: Michael Mclaughlin +// Definitions: https://github.com/MikeMcl/bignumber.js + +// Documentation: http://mikemcl.github.io/bignumber.js/ +// +// Exports: +// +// class BigNumber (default export) +// type BigNumber.Constructor +// type BigNumber.ModuloMode +// type BigNumber.RoundingMode +// type BigNumber.Value +// interface BigNumber.Config +// interface BigNumber.Format +// interface BigNumber.Instance +// +// Example: +// +// import {BigNumber} from "bignumber.js" +// //import BigNumber from "bignumber.js" +// +// let rm: BigNumber.RoundingMode = BigNumber.ROUND_UP; +// let f: BigNumber.Format = { decimalSeparator: ',' }; +// let c: BigNumber.Config = { DECIMAL_PLACES: 4, ROUNDING_MODE: rm, FORMAT: f }; +// BigNumber.config(c); +// +// let v: BigNumber.Value = '12345.6789'; +// let b: BigNumber = new BigNumber(v); +// +// The use of compiler option `--strictNullChecks` is recommended. + +export default BigNumber; + +export namespace BigNumber { + + /** See `BigNumber.config` (alias `BigNumber.set`) and `BigNumber.clone`. */ + interface Config { + + /** + * An integer, 0 to 1e+9. Default value: 20. + * + * The maximum number of decimal places of the result of operations involving division, i.e. + * division, square root and base conversion operations, and exponentiation when the exponent is + * negative. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BigNumber.set({ DECIMAL_PLACES: 5 }) + * ``` + */ + DECIMAL_PLACES?: number; + + /** + * An integer, 0 to 8. Default value: `BigNumber.ROUND_HALF_UP` (4). + * + * The rounding mode used in operations that involve division (see `DECIMAL_PLACES`) and the + * default rounding mode of the `decimalPlaces`, `precision`, `toExponential`, `toFixed`, + * `toFormat` and `toPrecision` methods. + * + * The modes are available as enumerated properties of the BigNumber constructor. + * + * ```ts + * BigNumber.config({ ROUNDING_MODE: 0 }) + * BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP }) + * ``` + */ + ROUNDING_MODE?: BigNumber.RoundingMode; + + /** + * An integer, 0 to 1e+9, or an array, [-1e+9 to 0, 0 to 1e+9]. + * Default value: `[-7, 20]`. + * + * The exponent value(s) at which `toString` returns exponential notation. + * + * If a single number is assigned, the value is the exponent magnitude. + * + * If an array of two numbers is assigned then the first number is the negative exponent value at + * and beneath which exponential notation is used, and the second number is the positive exponent + * value at and above which exponential notation is used. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they begin + * to use exponential notation, use `[-7, 20]`. + * + * ```ts + * BigNumber.config({ EXPONENTIAL_AT: 2 }) + * new BigNumber(12.3) // '12.3' e is only 1 + * new BigNumber(123) // '1.23e+2' + * new BigNumber(0.123) // '0.123' e is only -1 + * new BigNumber(0.0123) // '1.23e-2' + * + * BigNumber.config({ EXPONENTIAL_AT: [-7, 20] }) + * new BigNumber(123456789) // '123456789' e is only 8 + * new BigNumber(0.000000123) // '1.23e-7' + * + * // Almost never return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 1e+9 }) + * + * // Always return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 0 }) + * ``` + * + * Regardless of the value of `EXPONENTIAL_AT`, the `toFixed` method will always return a value in + * normal notation and the `toExponential` method will always return a value in exponential form. + * Calling `toString` with a base argument, e.g. `toString(10)`, will also always return normal + * notation. + */ + EXPONENTIAL_AT?: number | [number, number]; + + /** + * An integer, magnitude 1 to 1e+9, or an array, [-1e+9 to -1, 1 to 1e+9]. + * Default value: `[-1e+9, 1e+9]`. + * + * The exponent value(s) beyond which overflow to Infinity and underflow to zero occurs. + * + * If a single number is assigned, it is the maximum exponent magnitude: values wth a positive + * exponent of greater magnitude become Infinity and those with a negative exponent of greater + * magnitude become zero. + * + * If an array of two numbers is assigned then the first number is the negative exponent limit and + * the second number is the positive exponent limit. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they + * become zero and Infinity, use [-324, 308]. + * + * ```ts + * BigNumber.config({ RANGE: 500 }) + * BigNumber.config().RANGE // [ -500, 500 ] + * new BigNumber('9.999e499') // '9.999e+499' + * new BigNumber('1e500') // 'Infinity' + * new BigNumber('1e-499') // '1e-499' + * new BigNumber('1e-500') // '0' + * + * BigNumber.config({ RANGE: [-3, 4] }) + * new BigNumber(99999) // '99999' e is only 4 + * new BigNumber(100000) // 'Infinity' e is 5 + * new BigNumber(0.001) // '0.01' e is only -3 + * new BigNumber(0.0001) // '0' e is -4 + * ``` + * The largest possible magnitude of a finite BigNumber is 9.999...e+1000000000. + * The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. + */ + RANGE?: number | [number, number]; + + /** + * A boolean: `true` or `false`. Default value: `false`. + * + * The value that determines whether cryptographically-secure pseudo-random number generation is + * used. If `CRYPTO` is set to true then the random method will generate random digits using + * `crypto.getRandomValues` in browsers that support it, or `crypto.randomBytes` if using a + * version of Node.js that supports it. + * + * If neither function is supported by the host environment then attempting to set `CRYPTO` to + * `true` will fail and an exception will be thrown. + * + * If `CRYPTO` is `false` then the source of randomness used will be `Math.random` (which is + * assumed to generate at least 30 bits of randomness). + * + * See `BigNumber.random`. + * + * ```ts + * // Node.js + * global.crypto = require('crypto') + * + * BigNumber.config({ CRYPTO: true }) + * BigNumber.config().CRYPTO // true + * BigNumber.random() // 0.54340758610486147524 + * ``` + */ + CRYPTO?: boolean; + + /** + * An integer, 0, 1, 3, 6 or 9. Default value: `BigNumber.ROUND_DOWN` (1). + * + * The modulo mode used when calculating the modulus: `a mod n`. + * The quotient, `q = a / n`, is calculated according to the `ROUNDING_MODE` that corresponds to + * the chosen `MODULO_MODE`. + * The remainder, `r`, is calculated as: `r = a - n * q`. + * + * The modes that are most commonly used for the modulus/remainder operation are shown in the + * following table. Although the other rounding modes can be used, they may not give useful + * results. + * + * Property | Value | Description + * :------------------|:------|:------------------------------------------------------------------ + * `ROUND_UP` | 0 | The remainder is positive if the dividend is negative. + * `ROUND_DOWN` | 1 | The remainder has the same sign as the dividend. + * | | Uses 'truncating division' and matches JavaScript's `%` operator . + * `ROUND_FLOOR` | 3 | The remainder has the same sign as the divisor. + * | | This matches Python's `%` operator. + * `ROUND_HALF_EVEN` | 6 | The IEEE 754 remainder function. + * `EUCLID` | 9 | The remainder is always positive. + * | | Euclidian division: `q = sign(n) * floor(a / abs(n))` + * + * The rounding/modulo modes are available as enumerated properties of the BigNumber constructor. + * + * See `modulo`. + * + * ```ts + * BigNumber.config({ MODULO_MODE: BigNumber.EUCLID }) + * BigNumber.set({ MODULO_MODE: 9 }) // equivalent + * ``` + */ + MODULO_MODE?: BigNumber.ModuloMode; + + /** + * An integer, 0 to 1e+9. Default value: 0. + * + * The maximum precision, i.e. number of significant digits, of the result of the power operation + * - unless a modulus is specified. + * + * If set to 0, the number of significant digits will not be limited. + * + * See `exponentiatedBy`. + * + * ```ts + * BigNumber.config({ POW_PRECISION: 100 }) + * ``` + */ + POW_PRECISION?: number; + + /** + * An object including any number of the properties shown below. + * + * The object configures the format of the string returned by the `toFormat` method. + * The example below shows the properties of the object that are recognised, and + * their default values. + * + * Unlike the other configuration properties, the values of the properties of the `FORMAT` object + * will not be checked for validity - the existing object will simply be replaced by the object + * that is passed in. + * + * See `toFormat`. + * + * ```ts + * BigNumber.config({ + * FORMAT: { + * // string to prepend + * prefix: '', + * // the decimal separator + * decimalSeparator: '.', + * // the grouping separator of the integer part + * groupSeparator: ',', + * // the primary grouping size of the integer part + * groupSize: 3, + * // the secondary grouping size of the integer part + * secondaryGroupSize: 0, + * // the grouping separator of the fraction part + * fractionGroupSeparator: ' ', + * // the grouping size of the fraction part + * fractionGroupSize: 0, + * // string to append + * suffix: '' + * } + * }) + * ``` + */ + FORMAT?: BigNumber.Format; + + /** + * The alphabet used for base conversion. The length of the alphabet corresponds to the maximum + * value of the base argument that can be passed to the BigNumber constructor or `toString`. + * + * Default value: `'0123456789abcdefghijklmnopqrstuvwxyz'`. + * + * There is no maximum length for the alphabet, but it must be at least 2 characters long, + * and it must not contain whitespace or a repeated character, or the sign indicators '+' and + * '-', or the decimal separator '.'. + * + * ```ts + * // duodecimal (base 12) + * BigNumber.config({ ALPHABET: '0123456789TE' }) + * x = new BigNumber('T', 12) + * x.toString() // '10' + * x.toString(12) // 'T' + * ``` + */ + ALPHABET?: string; + } + + /** See `FORMAT` and `toFormat`. */ + interface Format { + + /** The string to prepend. */ + prefix?: string; + + /** The decimal separator. */ + decimalSeparator?: string; + + /** The grouping separator of the integer part. */ + groupSeparator?: string; + + /** The primary grouping size of the integer part. */ + groupSize?: number; + + /** The secondary grouping size of the integer part. */ + secondaryGroupSize?: number; + + /** The grouping separator of the fraction part. */ + fractionGroupSeparator?: string; + + /** The grouping size of the fraction part. */ + fractionGroupSize?: number; + + /** The string to append. */ + suffix?: string; + } + + interface Instance { + + /** The coefficient of the value of this BigNumber, an array of base 1e14 integer numbers, or null. */ + readonly c: number[] | null; + + /** The exponent of the value of this BigNumber, an integer number, -1000000000 to 1000000000, or null. */ + readonly e: number | null; + + /** The sign of the value of this BigNumber, -1, 1, or null. */ + readonly s: number | null; + + [key: string]: any; + } + + type Constructor = typeof BigNumber; + type ModuloMode = 0 | 1 | 3 | 6 | 9; + type RoundingMode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + type Value = string | number | Instance; +} + +export declare class BigNumber implements BigNumber.Instance { + + /** Used internally to identify a BigNumber instance. */ + private readonly _isBigNumber: true; + + /** The coefficient of the value of this BigNumber, an array of base 1e14 integer numbers, or null. */ + readonly c: number[] | null; + + /** The exponent of the value of this BigNumber, an integer number, -1000000000 to 1000000000, or null. */ + readonly e: number | null; + + /** The sign of the value of this BigNumber, -1, 1, or null. */ + readonly s: number | null; + + /** + * Returns a new instance of a BigNumber object with value `n`, where `n` is a numeric value in + * the specified `base`, or base 10 if `base` is omitted or is `null` or `undefined`. + * + * ```ts + * x = new BigNumber(123.4567) // '123.4567' + * // 'new' is optional + * y = BigNumber(x) // '123.4567' + * ``` + * + * If `n` is a base 10 value it can be in normal (fixed-point) or exponential notation. + * Values in other bases must be in normal notation. Values in any base can have fraction digits, + * i.e. digits after the decimal point. + * + * ```ts + * new BigNumber(43210) // '43210' + * new BigNumber('4.321e+4') // '43210' + * new BigNumber('-735.0918e-430') // '-7.350918e-428' + * new BigNumber('123412421.234324', 5) // '607236.557696' + * ``` + * + * Signed `0`, signed `Infinity` and `NaN` are supported. + * + * ```ts + * new BigNumber('-Infinity') // '-Infinity' + * new BigNumber(NaN) // 'NaN' + * new BigNumber(-0) // '0' + * new BigNumber('.5') // '0.5' + * new BigNumber('+2') // '2' + * ``` + * + * String values in hexadecimal literal form, e.g. `'0xff'`, are valid, as are string values with + * the octal and binary prefixs `'0o'` and `'0b'`. String values in octal literal form without the + * prefix will be interpreted as decimals, e.g. `'011'` is interpreted as 11, not 9. + * + * ```ts + * new BigNumber(-10110100.1, 2) // '-180.5' + * new BigNumber('-0b10110100.1') // '-180.5' + * new BigNumber('ff.8', 16) // '255.5' + * new BigNumber('0xff.8') // '255.5' + * ``` + * + * If a base is specified, `n` is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. This includes base 10, so don't include a `base` parameter for decimal + * values unless this behaviour is desired. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * new BigNumber(1.23456789) // '1.23456789' + * new BigNumber(1.23456789, 10) // '1.23457' + * ``` + * + * An error is thrown if `base` is invalid. + * + * There is no limit to the number of digits of a value of type string (other than that of + * JavaScript's maximum array size). See `RANGE` to set the maximum and minimum possible exponent + * value of a BigNumber. + * + * ```ts + * new BigNumber('5032485723458348569331745.33434346346912144534543') + * new BigNumber('4.321e10000000') + * ``` + * + * BigNumber `NaN` is returned if `n` is invalid (unless `BigNumber.DEBUG` is `true`, see below). + * + * ```ts + * new BigNumber('.1*') // 'NaN' + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * ``` + * + * To aid in debugging, if `BigNumber.DEBUG` is `true` then an error will be thrown on an + * invalid `n`. An error will also be thrown if `n` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on these numbers may not result in the + * intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * // 'Error: Number has more than 15 significant digits' + * new BigNumber(823456789123456.3) + * // 'Error: Not a base 2 number' + * new BigNumber(9, 2) + * ``` + * + * A BigNumber can also be created from an object literal. + * Use `isBigNumber` to check that it is well-formed. + * + * ```ts + * new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true }) // '777.123' + * ``` + * + * @param n A numeric value. + * @param base The base of `n`, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + constructor(n: BigNumber.Value, base?: number); + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.absoluteValue() // '0.8' + * ``` + */ + absoluteValue(): BigNumber; + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.abs() // '0.8' + * ``` + */ + abs(): BigNumber; + + /** + * Returns | | + * :-------:|:--------------------------------------------------------------| + * 1 | If the value of this BigNumber is greater than the value of `n` + * -1 | If the value of this BigNumber is less than the value of `n` + * 0 | If this BigNumber and `n` have the same value + * `null` | If the value of either this BigNumber or `n` is `NaN` + * + * ```ts + * + * x = new BigNumber(Infinity) + * y = new BigNumber(5) + * x.comparedTo(y) // 1 + * x.comparedTo(x.minus(1)) // 0 + * y.comparedTo(NaN) // null + * y.comparedTo('110', 2) // -1 + * ``` + * @param n A numeric value. + * @param [base] The base of n. + */ + comparedTo(n: BigNumber.Value, base?: number): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the return value is the number of + * decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is + * ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.decimalPlaces() // 2 + * x.decimalPlaces(1) // '1234.6' + * x.decimalPlaces(2) // '1234.56' + * x.decimalPlaces(10) // '1234.56' + * x.decimalPlaces(0, 1) // '1234' + * x.decimalPlaces(0, 6) // '1235' + * x.decimalPlaces(1, 1) // '1234.5' + * x.decimalPlaces(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.decimalPlaces() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + decimalPlaces(): number | null; + decimalPlaces(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the return value is the number of + * decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is + * ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.dp() // 2 + * x.dp(1) // '1234.6' + * x.dp(2) // '1234.56' + * x.dp(10) // '1234.56' + * x.dp(0, 1) // '1234' + * x.dp(0, 6) // '1235' + * x.dp(1, 1) // '1234.5' + * x.dp(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.dp() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + dp(): number | null; + dp(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.dividedBy(y) // '3.14159292035398230088' + * x.dividedBy(5) // '71' + * x.dividedBy(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.div(y) // '3.14159292035398230088' + * x.div(5) // '71' + * x.div(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + div(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.dividedToIntegerBy(y) // '1' + * x.dividedToIntegerBy(0.7) // '7' + * x.dividedToIntegerBy('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedToIntegerBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.idiv(y) // '1' + * x.idiv(0.7) // '7' + * x.idiv('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + idiv(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.exponentiatedBy(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.exponentiatedBy(2) // '0.49' + * BigNumber(3).exponentiatedBy(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + exponentiatedBy(n: BigNumber.Value, m?: BigNumber.Value): BigNumber; + exponentiatedBy(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.pow(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.pow(2) // '0.49' + * BigNumber(3).pow(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + pow(n: BigNumber.Value, m?: BigNumber.Value): BigNumber; + pow(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + * rounding mode `rm`. + * + * If `rm` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `rm` is invalid. + * + * ```ts + * x = new BigNumber(123.456) + * x.integerValue() // '123' + * x.integerValue(BigNumber.ROUND_CEIL) // '124' + * y = new BigNumber(-12.7) + * y.integerValue() // '-13' + * x.integerValue(BigNumber.ROUND_DOWN) // '-12' + * ``` + * + * @param {BigNumber.RoundingMode} [rm] The roundng mode, an integer, 0 to 8. + */ + integerValue(rm?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.isEqualTo('1e-324') // false + * BigNumber(-0).isEqualTo(x) // true ( -0 === 0 ) + * BigNumber(255).isEqualTo('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.isEqualTo(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.eq('1e-324') // false + * BigNumber(-0).eq(x) // true ( -0 === 0 ) + * BigNumber(255).eq('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.eq(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + eq(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is a finite number, otherwise returns `false`. + * + * The only possible non-finite values of a BigNumber are `NaN`, `Infinity` and `-Infinity`. + * + * ```ts + * x = new BigNumber(1) + * x.isFinite() // true + * y = new BigNumber(Infinity) + * y.isFinite() // false + * ``` + */ + isFinite(): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0.2) // true + * x = new BigNumber(0.1) + * x.isGreaterThan(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).isGreaterThan(x) // false + * BigNumber(11, 3).isGreaterThan(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0 // true + * x = new BigNumber(0.1) + * x.gt(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).gt(x) // false + * BigNumber(11, 3).gt(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.isGreaterThanOrEqualTo(0.1) // true + * BigNumber(1).isGreaterThanOrEqualTo(x) // true + * BigNumber(10, 18).isGreaterThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.gte(0.1) // true + * BigNumber(1).gte(x) // true + * BigNumber(10, 18).gte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is an integer, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(1) + * x.isInteger() // true + * y = new BigNumber(123.456) + * y.isInteger() // false + * ``` + */ + isInteger(): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.isLessThan(0.1) // false + * BigNumber(0).isLessThan(x) // true + * BigNumber(11.1, 2).isLessThan(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.lt(0.1) // false + * BigNumber(0).lt(x) // true + * BigNumber(11.1, 2).lt(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).isLessThanOrEqualTo(x) // true + * BigNumber(10, 18).isLessThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.lte(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).lte(x) // true + * BigNumber(10, 18).lte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is `NaN`, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(NaN) + * x.isNaN() // true + * y = new BigNumber('Infinity') + * y.isNaN() // false + * ``` + */ + isNaN(): boolean; + + /** + * Returns `true` if the value of this BigNumber is negative, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isNegative() // true + * y = new BigNumber(2) + * y.isNegative() // false + * ``` + */ + isNegative(): boolean; + + /** + * Returns `true` if the value of this BigNumber is positive, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isPositive() // false + * y = new BigNumber(2) + * y.isPositive() // true + * ``` + */ + isPositive(): boolean; + + /** + * Returns `true` if the value of this BigNumber is zero or minus zero, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isZero() // true + * ``` + */ + isZero(): boolean; + + /** + * Returns a BigNumber whose value is the value of this BigNumber minus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.3 - 0.1 // 0.19999999999999998 + * x = new BigNumber(0.3) + * x.minus(0.1) // '0.2' + * x.minus(0.6, 20) // '0' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + minus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.modulo(0.9) // '0.1' + * y = new BigNumber(33) + * y.modulo('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + modulo(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.mod(0.9) // '0.1' + * y = new BigNumber(33) + * y.mod('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + mod(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.multipliedBy(3) // '1.8' + * BigNumber('7e+500').multipliedBy(y) // '1.26e+501' + * x.multipliedBy('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + multipliedBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.times(3) // '1.8' + * BigNumber('7e+500').times(y) // '1.26e+501' + * x.times('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + times(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by -1. + * + * ```ts + * x = new BigNumber(1.8) + * x.negated() // '-1.8' + * y = new BigNumber(-1.3) + * y.negated() // '1.3' + * ``` + */ + negated(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber plus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.1 + 0.2 // 0.30000000000000004 + * x = new BigNumber(0.1) + * y = x.plus(0.2) // '0.3' + * BigNumber(0.7).plus(x).plus(y) // '1.1' + * x.plus('0.1', 8) // '0.225' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + plus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, or `null` if the value + * of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of the value of this + * BigNumber are counted as significant digits, otherwise they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision() // 9 + * y = new BigNumber(987000) + * y.precision(false) // 3 + * y.precision(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + precision(includeZeros?: boolean): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision(6) // '9876.54' + * x.precision(6, BigNumber.ROUND_UP) // '9876.55' + * x.precision(2) // '9900' + * x.precision(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + precision(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, + * or `null` if the value of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of + * the value of this BigNumber are counted as significant digits, otherwise + * they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd() // 9 + * y = new BigNumber(987000) + * y.sd(false) // 3 + * y.sd(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + sd(includeZeros?: boolean): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd(6) // '9876.54' + * x.sd(6, BigNumber.ROUND_UP) // '9876.55' + * x.sd(2) // '9900' + * x.sd(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + sd(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber shifted by `n` places. + * + * The shift is of the decimal point, i.e. of powers of ten, and is to the left if `n` is negative + * or to the right if `n` is positive. + * + * The return value is always exact and unrounded. + * + * Throws if `n` is invalid. + * + * ```ts + * x = new BigNumber(1.23) + * x.shiftedBy(3) // '1230' + * x.shiftedBy(-3) // '0.00123' + * ``` + * + * @param n The shift value, integer, -9007199254740991 to 9007199254740991. + */ + shiftedBy(n: number): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.squareRoot() // '4' + * y = new BigNumber(3) + * y.squareRoot() // '1.73205080756887729353' + * ``` + */ + squareRoot(): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.sqrt() // '4' + * y = new BigNumber(3) + * y.sqrt() // '1.73205080756887729353' + * ``` + */ + sqrt(): BigNumber; + + /** + * Returns a string representing the value of this BigNumber in exponential notation rounded using + * rounding mode `roundingMode` to `decimalPlaces` decimal places, i.e with one digit before the + * decimal point and `decimalPlaces` digits after it. + * + * If the value of this BigNumber in exponential notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the number of digits after the + * decimal point defaults to the minimum number of digits necessary to represent the value + * exactly. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toExponential() // '4.56e+1' + * y.toExponential() // '4.56e+1' + * x.toExponential(0) // '5e+1' + * y.toExponential(0) // '5e+1' + * x.toExponential(1) // '4.6e+1' + * y.toExponential(1) // '4.6e+1' + * y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN) + * x.toExponential(3) // '4.560e+1' + * y.toExponential(3) // '4.560e+1' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toExponential(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toExponential(): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`. + * + * If the value of this BigNumber in normal notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * Unlike `Number.prototype.toFixed`, which returns exponential notation if a number is greater or + * equal to 10**21, this method will always return normal notation. + * + * If `decimalPlaces` is omitted or is `null` or `undefined`, the return value will be unrounded + * and in normal notation. This is also unlike `Number.prototype.toFixed`, which returns the value + * to zero decimal places. It is useful when normal notation is required and the current + * `EXPONENTIAL_AT` setting causes `toString` to return exponential notation. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 3.456 + * y = new BigNumber(x) + * x.toFixed() // '3' + * y.toFixed() // '3.456' + * y.toFixed(0) // '3' + * x.toFixed(2) // '3.46' + * y.toFixed(2) // '3.46' + * y.toFixed(2, 1) // '3.45' (ROUND_DOWN) + * x.toFixed(5) // '3.45600' + * y.toFixed(5) // '3.45600' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toFixed(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toFixed(): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`, and formatted + * according to the properties of the `format` or `FORMAT` object. + * + * The formatting object may contain some or all of the properties shown in the examples below. + * + * If `decimalPlaces` is omitted or is `null` or `undefined`, then the return value is not + * rounded to a fixed number of decimal places. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * If `format` is omitted or is `null` or `undefined`, `FORMAT` is used. + * + * Throws if `decimalPlaces`, `roundingMode`, or `format` is invalid. + * + * ```ts + * fmt = { + * decimalSeparator: '.', + * groupSeparator: ',', + * groupSize: 3, + * secondaryGroupSize: 0, + * fractionGroupSeparator: ' ', + * fractionGroupSize: 0 + * } + * + * x = new BigNumber('123456789.123456789') + * + * // Set the global formatting options + * BigNumber.config({ FORMAT: fmt }) + * + * x.toFormat() // '123,456,789.123456789' + * x.toFormat(3) // '123,456,789.123' + * + * // If a reference to the object assigned to FORMAT has been retained, + * // the format properties can be changed directly + * fmt.groupSeparator = ' ' + * fmt.fractionGroupSize = 5 + * x.toFormat() // '123 456 789.12345 6789' + * + * // Alternatively, pass the formatting options as an argument + * fmt = { + * decimalSeparator: ',', + * groupSeparator: '.', + * groupSize: 3, + * secondaryGroupSize: 2 + * } + * + * x.toFormat() // '123 456 789.12345 6789' + * x.toFormat(fmt) // '12.34.56.789,123456789' + * x.toFormat(2, fmt) // '12.34.56.789,12' + * x.toFormat(3, BigNumber.ROUND_UP, fmt) // '12.34.56.789,124' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + * @param [format] Formatting options object. See `BigNumber.Format`. + */ + toFormat(decimalPlaces: number, roundingMode: BigNumber.RoundingMode, format?: BigNumber.Format): string; + toFormat(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toFormat(decimalPlaces?: number): string; + toFormat(decimalPlaces: number, format: BigNumber.Format): string; + toFormat(format: BigNumber.Format): string; + + /** + * Returns 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 `max_denominator`. + * If a maximum denominator, `max_denominator`, is not specified, or is `null` or `undefined`, the + * denominator will be the lowest value necessary to represent the number exactly. + * + * Throws if `max_denominator` is invalid. + * + * ```ts + * x = new BigNumber(1.75) + * x.toFraction() // '7, 4' + * + * pi = new BigNumber('3.14159265358') + * pi.toFraction() // '157079632679,50000000000' + * pi.toFraction(100000) // '312689, 99532' + * pi.toFraction(10000) // '355, 113' + * pi.toFraction(100) // '311, 99' + * pi.toFraction(10) // '22, 7' + * pi.toFraction(1) // '3, 1' + * ``` + * + * @param [max_denominator] The maximum denominator, integer > 0, or Infinity. + */ + toFraction(max_denominator?: BigNumber.Value): [BigNumber, BigNumber]; + + /** As `valueOf`. */ + toJSON(): string; + + /** + * Returns the value of this BigNumber as a JavaScript primitive number. + * + * Using the unary plus operator gives the same result. + * + * ```ts + * x = new BigNumber(456.789) + * x.toNumber() // 456.789 + * +x // 456.789 + * + * y = new BigNumber('45987349857634085409857349856430985') + * y.toNumber() // 4.598734985763409e+34 + * + * z = new BigNumber(-0) + * 1 / z.toNumber() // -Infinity + * 1 / +z // -Infinity + * ``` + */ + toNumber(): number; + + /** + * Returns a string representing the value of this BigNumber rounded to `significantDigits` + * significant digits using rounding mode `roundingMode`. + * + * If `significantDigits` is less than the number of digits necessary to represent the integer + * part of the value in normal (fixed-point) notation, then exponential notation is used. + * + * If `significantDigits` is omitted, or is `null` or `undefined`, then the return value is the + * same as `n.toString()`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toPrecision() // '45.6' + * y.toPrecision() // '45.6' + * x.toPrecision(1) // '5e+1' + * y.toPrecision(1) // '5e+1' + * y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP) + * y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN) + * x.toPrecision(5) // '45.600' + * y.toPrecision(5) // '45.600' + * ``` + * + * @param [significantDigits] Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer 0 to 8. + */ + toPrecision(significantDigits: number, roundingMode?: BigNumber.RoundingMode): string; + toPrecision(): string; + + /** + * Returns a string representing the value of this BigNumber in base `base`, or base 10 if `base` + * is omitted or is `null` or `undefined`. + * + * For bases above 10, and using the default base conversion alphabet (see `ALPHABET`), values + * from 10 to 35 are represented by a-z (the same as `Number.prototype.toString`). + * + * If a base is specified the value is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings, otherwise it is not. + * + * If a base is not specified, and this BigNumber has a positive exponent that is equal to or + * greater than the positive component of the current `EXPONENTIAL_AT` setting, or a negative + * exponent equal to or less than the negative component of the setting, then exponential notation + * is returned. + * + * If `base` is `null` or `undefined` it is ignored. + * + * Throws if `base` is invalid. + * + * ```ts + * x = new BigNumber(750000) + * x.toString() // '750000' + * BigNumber.config({ EXPONENTIAL_AT: 5 }) + * x.toString() // '7.5e+5' + * + * y = new BigNumber(362.875) + * y.toString(2) // '101101010.111' + * y.toString(9) // '442.77777777777777777778' + * y.toString(32) // 'ba.s' + * + * BigNumber.config({ DECIMAL_PLACES: 4 }); + * z = new BigNumber('1.23456789') + * z.toString() // '1.23456789' + * z.toString(10) // '1.2346' + * ``` + * + * @param [base] The base, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + toString(base?: number): string; + + /** + * As `toString`, but does not accept a base argument and includes the minus sign for negative + * zero. + * + * ``ts + * x = new BigNumber('-0') + * x.toString() // '0' + * x.valueOf() // '-0' + * y = new BigNumber('1.777e+457') + * y.valueOf() // '1.777e+457' + * ``` + */ + valueOf(): string; + + /** Helps ES6 import. */ + private static readonly default?: BigNumber.Constructor; + + /** Helps ES6 import. */ + private static readonly BigNumber?: BigNumber.Constructor; + + /** Rounds away from zero. */ + static readonly ROUND_UP: 0; + + /** Rounds towards zero. */ + static readonly ROUND_DOWN: 1; + + /** Rounds towards Infinity. */ + static readonly ROUND_CEIL: 2; + + /** Rounds towards -Infinity. */ + static readonly ROUND_FLOOR: 3; + + /** Rounds towards nearest neighbour. If equidistant, rounds away from zero . */ + static readonly ROUND_HALF_UP: 4; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards zero. */ + static readonly ROUND_HALF_DOWN: 5; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour. */ + static readonly ROUND_HALF_EVEN: 6; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards Infinity. */ + static readonly ROUND_HALF_CEIL: 7; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards -Infinity. */ + static readonly ROUND_HALF_FLOOR: 8; + + /** See `MODULO_MODE`. */ + static readonly EUCLID: 9; + + /** + * To aid in debugging, if a `BigNumber.DEBUG` property is `true` then an error will be thrown + * if the BigNumber constructor receives an invalid `BigNumber.Value`, or if `BigNumber.isBigNumber` + * receives a BigNumber instance that is malformed. + * + * ```ts + * // No error, and BigNumber NaN is returned. + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * BigNumber.DEBUG = true + * new BigNumber('blurgh') // '[BigNumber Error] Not a number' + * new BigNumber(9, 2) // '[BigNumber Error] Not a base 2 number' + * ``` + * + * An error will also be thrown if a `BigNumber.Value` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on such numbers may not result + * in the intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * // No error, and the returned BigNumber does not have the same value as the number literal. + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * new BigNumber(823456789123456.3) + * // '[BigNumber Error] Number primitive has more than 15 significant digits' + * ``` + * + * Check that a BigNumber instance is well-formed: + * + * ```ts + * x = new BigNumber(10) + * + * BigNumber.DEBUG = false + * // Change x.c to an illegitimate value. + * x.c = NaN + * // No error, as BigNumber.DEBUG is false. + * BigNumber.isBigNumber(x) // true + * + * BigNumber.DEBUG = true + * BigNumber.isBigNumber(x) // '[BigNumber Error] Invalid BigNumber' + * ``` + */ + static DEBUG?: boolean; + + /** + * Returns a new independent BigNumber constructor with configuration as described by `object`, or + * with the default configuration if object is `null` or `undefined`. + * + * Throws if `object` is not an object. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) + * + * x = new BigNumber(1) + * y = new BN(1) + * + * x.div(3) // 0.33333 + * y.div(3) // 0.333333333 + * + * // BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to: + * BN = BigNumber.clone() + * BN.config({ DECIMAL_PLACES: 9 }) + * ``` + * + * @param [object] The configuration object. + */ + static clone(object?: BigNumber.Config): BigNumber.Constructor; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.config({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.config().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static config(object?: BigNumber.Config): BigNumber.Config; + + /** + * Returns `true` if `value` is a BigNumber instance, otherwise returns `false`. + * + * If `BigNumber.DEBUG` is `true`, throws if a BigNumber instance is not well-formed. + * + * ```ts + * x = 42 + * y = new BigNumber(x) + * + * BigNumber.isBigNumber(x) // false + * y instanceof BigNumber // true + * BigNumber.isBigNumber(y) // true + * + * BN = BigNumber.clone(); + * z = new BN(x) + * z instanceof BigNumber // false + * BigNumber.isBigNumber(z) // true + * ``` + * + * @param value The value to test. + */ + static isBigNumber(value: any): value is BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.maximum(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.maximum.apply(null, arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static maximum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.max(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.max.apply(null, arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static max(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.minimum(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.minimum.apply(null, arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static minimum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.min(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.min.apply(null, arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static min(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and less than 1. + * + * The return value will have `decimalPlaces` decimal places, or less if trailing zeros are + * produced. If `decimalPlaces` is omitted, the current `DECIMAL_PLACES` setting will be used. + * + * Depending on the value of this BigNumber constructor's `CRYPTO` setting and the support for the + * `crypto` object in the host environment, the random digits of the return value are generated by + * either `Math.random` (fastest), `crypto.getRandomValues` (Web Cryptography API in recent + * browsers) or `crypto.randomBytes` (Node.js). + * + * To be able to set `CRYPTO` to true when using Node.js, the `crypto` object must be available + * globally: + * + * ```ts + * global.crypto = require('crypto') + * ``` + * + * If `CRYPTO` is true, i.e. one of the `crypto` methods is to be used, the value of a returned + * BigNumber should be cryptographically secure and statistically indistinguishable from a random + * value. + * + * Throws if `decimalPlaces` is invalid. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 10 }) + * BigNumber.random() // '0.4117936847' + * BigNumber.random(20) // '0.78193327636914089009' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + */ + static random(decimalPlaces?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the sum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.sum(4e9, x, '123456789.9') // '7381326134.9378653' + * + * arr = [2, new BigNumber(14), '15.9999', 12] + * BigNumber.sum.apply(null, arr) // '43.9999' + * ``` + * + * @param n A numeric value. + */ + static sum(...n: BigNumber.Value[]): BigNumber; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.set({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.set().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static set(object?: BigNumber.Config): BigNumber.Config; +} + +export function BigNumber(n: BigNumber.Value, base?: number): BigNumber; diff --git a/node_modules/bignumber.js/bignumber.js b/node_modules/bignumber.js/bignumber.js new file mode 100644 index 0000000..e5c66c8 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.js @@ -0,0 +1,2922 @@ +;(function (globalObject) { + 'use strict'; + +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 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; + 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 (typeof module != 'undefined' && module.exports) { + module.exports = BigNumber; + + // Browser. + } else { + if (!globalObject) { + globalObject = typeof self != 'undefined' && self ? self : window; + } + + globalObject.BigNumber = BigNumber; + } +})(this); diff --git a/node_modules/bignumber.js/bignumber.mjs b/node_modules/bignumber.js/bignumber.mjs new file mode 100644 index 0000000..f154015 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.mjs @@ -0,0 +1,2907 @@ +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 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 + 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; + 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; + + P[Symbol.toStringTag] = 'BigNumber'; + + // Node.js v10.12.0+ + P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf; + + 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 + + +export var BigNumber = clone(); + +export default BigNumber; diff --git a/node_modules/bignumber.js/doc/API.html b/node_modules/bignumber.js/doc/API.html new file mode 100644 index 0000000..bb2b7dd --- /dev/null +++ b/node_modules/bignumber.js/doc/API.html @@ -0,0 +1,2249 @@ + + + + + + +bignumber.js API + + + + +
+ +
+ +

bignumber.js

+ +

A JavaScript library for arbitrary-precision arithmetic.

+

Hosted on GitHub.

+ +

API

+ +

+ See the README on GitHub for a + quick-start introduction. +

+

+ In all examples below, var and semicolons are not shown, and if a commented-out + value is in quotes it means toString has been called on the preceding expression. +

+ + +

CONSTRUCTOR

+ + +
+ BigNumberBigNumber(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number: integer, 2 to 36 inclusive. (See + ALPHABET to extend this range). +

+

+ Returns a new instance of a BigNumber object with value n, where n + is a numeric value in the specified base, or base 10 if + base is omitted or is null or undefined. +

+

+ Note that the BigNnumber constructor accepts an n of type number purely + as a convenience so that string quotes don't have to be typed when entering literal values, + and that it is the toString value of n that is used rather than its + underlying binary floating point value converted to decimal. +

+
+x = new BigNumber(123.4567)                // '123.4567'
+// 'new' is optional
+y = BigNumber(x)                           // '123.4567'
+

+ If n is a base 10 value it can be in normal or exponential notation. + Values in other bases must be in normal notation. Values in any base can have fraction digits, + i.e. digits after the decimal point. +

+
+new BigNumber(43210)                       // '43210'
+new BigNumber('4.321e+4')                  // '43210'
+new BigNumber('-735.0918e-430')            // '-7.350918e-428'
+new BigNumber('123412421.234324', 5)       // '607236.557696'
+

+ Signed 0, signed Infinity and NaN are supported. +

+
+new BigNumber('-Infinity')                 // '-Infinity'
+new BigNumber(NaN)                         // 'NaN'
+new BigNumber(-0)                          // '0'
+new BigNumber('.5')                        // '0.5'
+new BigNumber('+2')                        // '2'
+

+ String values in hexadecimal literal form, e.g. '0xff' or '0xFF' + (but not '0xfF'), are valid, as are string values with the octal and binary + prefixs '0o' and '0b'. String values in octal literal form without + the prefix will be interpreted as decimals, e.g. '011' is interpreted as 11, not 9. +

+
+new BigNumber(-10110100.1, 2)              // '-180.5'
+new BigNumber('-0b10110100.1')             // '-180.5'
+new BigNumber('ff.8', 16)                  // '255.5'
+new BigNumber('0xff.8')                    // '255.5'
+

+ If a base is specified, n is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. This includes base + 10 so don't include a base parameter for decimal values unless + this behaviour is wanted. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+new BigNumber(1.23456789)                  // '1.23456789'
+new BigNumber(1.23456789, 10)              // '1.23457'
+

An error is thrown if base is invalid. See Errors.

+

+ There is no limit to the number of digits of a value of type string (other than + that of JavaScript's maximum array size). See RANGE to set + the maximum and minimum possible exponent value of a BigNumber. +

+
+new BigNumber('5032485723458348569331745.33434346346912144534543')
+new BigNumber('4.321e10000000')
+

BigNumber NaN is returned if n is invalid + (unless BigNumber.DEBUG is true, see below).

+
+new BigNumber('.1*')                       // 'NaN'
+new BigNumber('blurgh')                    // 'NaN'
+new BigNumber(9, 2)                        // 'NaN'
+

+ To aid in debugging, if BigNumber.DEBUG is true then an error will + be thrown on an invalid n. An error will also be thrown if n is of + type number and has more than 15 significant digits, as calling + toString or valueOf on + these numbers may not result in the intended value. +

+
+console.log(823456789123456.3)            //  823456789123456.2
+new BigNumber(823456789123456.3)          // '823456789123456.2'
+BigNumber.DEBUG = true
+// '[BigNumber Error] Number primitive has more than 15 significant digits'
+new BigNumber(823456789123456.3)
+// '[BigNumber Error] Not a base 2 number'
+new BigNumber(9, 2)
+

+ A BigNumber can also be created from an object literal. + Use isBigNumber to check that it is well-formed. +

+
new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true })    // '777.123'
+ + + + +

Methods

+

The static methods of a BigNumber constructor.

+ + + + +
clone + .clone([object]) ⇒ BigNumber constructor +
+

object: object

+

+ Returns a new independent BigNumber constructor with configuration as described by + object (see config), or with the default + configuration if object is null or undefined. +

+

+ Throws if object is not an object. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BN = BigNumber.clone({ DECIMAL_PLACES: 9 })
+
+x = new BigNumber(1)
+y = new BN(1)
+
+x.div(3)                        // 0.33333
+y.div(3)                        // 0.333333333
+
+// BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to:
+BN = BigNumber.clone()
+BN.config({ DECIMAL_PLACES: 9 })
+ + + +
configset([object]) ⇒ object
+

+ object: object: an object that contains some or all of the following + properties. +

+

Configures the settings for this particular BigNumber constructor.

+ +
+
DECIMAL_PLACES
+
+ number: integer, 0 to 1e+9 inclusive
+ Default value: 20 +
+
+ The maximum number of decimal places of the results of operations involving + division, i.e. division, square root and base conversion operations, and power operations + with negative exponents.
+
+
+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BigNumber.set({ DECIMAL_PLACES: 5 })    // equivalent
+
+ + + +
ROUNDING_MODE
+
+ number: integer, 0 to 8 inclusive
+ Default value: 4 (ROUND_HALF_UP) +
+
+ The rounding mode used in the above operations and the default rounding mode of + decimalPlaces, + precision, + toExponential, + toFixed, + toFormat and + toPrecision. +
+
The modes are available as enumerated properties of the BigNumber constructor.
+
+
BigNumber.config({ ROUNDING_MODE: 0 })
+BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP })    // equivalent
+
+ + + +
EXPONENTIAL_AT
+
+ number: integer, magnitude 0 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to 0 inclusive, integer + 0 to 1e+9 inclusive ]
+ Default value: [-7, 20] +
+
+ The exponent value(s) at which toString returns exponential notation. +
+
+ If a single number is assigned, the value is the exponent magnitude.
+ If an array of two numbers is assigned then the first number is the negative exponent + value at and beneath which exponential notation is used, and the second number is the + positive exponent value at and above which the same. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + begin to use exponential notation, use [-7, 20]. +
+
+
BigNumber.config({ EXPONENTIAL_AT: 2 })
+new BigNumber(12.3)         // '12.3'        e is only 1
+new BigNumber(123)          // '1.23e+2'
+new BigNumber(0.123)        // '0.123'       e is only -1
+new BigNumber(0.0123)       // '1.23e-2'
+
+BigNumber.config({ EXPONENTIAL_AT: [-7, 20] })
+new BigNumber(123456789)    // '123456789'   e is only 8
+new BigNumber(0.000000123)  // '1.23e-7'
+
+// Almost never return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
+
+// Always return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 0 })
+
+
+ Regardless of the value of EXPONENTIAL_AT, the toFixed method + will always return a value in normal notation and the toExponential method + will always return a value in exponential form. +
+
+ Calling toString with a base argument, e.g. toString(10), will + also always return normal notation. +
+ + + +
RANGE
+
+ number: integer, magnitude 1 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to -1 inclusive, integer + 1 to 1e+9 inclusive ]
+ Default value: [-1e+9, 1e+9] +
+
+ The exponent value(s) beyond which overflow to Infinity and underflow to + zero occurs. +
+
+ If a single number is assigned, it is the maximum exponent magnitude: values wth a + positive exponent of greater magnitude become Infinity and those with a + negative exponent of greater magnitude become zero. +
+ If an array of two numbers is assigned then the first number is the negative exponent + limit and the second number is the positive exponent limit. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + become zero and Infinity, use [-324, 308]. +
+
+
BigNumber.config({ RANGE: 500 })
+BigNumber.config().RANGE     // [ -500, 500 ]
+new BigNumber('9.999e499')   // '9.999e+499'
+new BigNumber('1e500')       // 'Infinity'
+new BigNumber('1e-499')      // '1e-499'
+new BigNumber('1e-500')      // '0'
+
+BigNumber.config({ RANGE: [-3, 4] })
+new BigNumber(99999)         // '99999'      e is only 4
+new BigNumber(100000)        // 'Infinity'   e is 5
+new BigNumber(0.001)         // '0.01'       e is only -3
+new BigNumber(0.0001)        // '0'          e is -4
+
+
+ The largest possible magnitude of a finite BigNumber is + 9.999...e+1000000000.
+ The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. +
+ + + +
CRYPTO
+
+ boolean: true or false.
+ Default value: false +
+
+ The value that determines whether cryptographically-secure pseudo-random number + generation is used. +
+
+ If CRYPTO is set to true then the + random method will generate random digits using + crypto.getRandomValues in browsers that support it, or + crypto.randomBytes if using Node.js. +
+
+ If neither function is supported by the host environment then attempting to set + CRYPTO to true will fail and an exception will be thrown. +
+
+ If CRYPTO is false then the source of randomness used will be + Math.random (which is assumed to generate at least 30 bits of + randomness). +
+
See random.
+
+
+// Node.js
+const crypto = require('crypto');   // CommonJS
+import * as crypto from 'crypto';   // ES module
+
+global.crypto = crypto;
+
+BigNumber.config({ CRYPTO: true })
+BigNumber.config().CRYPTO       // true
+BigNumber.random()              // 0.54340758610486147524
+
+ + + +
MODULO_MODE
+
+ number: integer, 0 to 9 inclusive
+ Default value: 1 (ROUND_DOWN) +
+
The modulo mode used when calculating the modulus: a mod n.
+
+ The quotient, q = a / n, is calculated according to the + ROUNDING_MODE that corresponds to the chosen + MODULO_MODE. +
+
The remainder, r, is calculated as: r = a - n * q.
+
+ The modes that are most commonly used for the modulus/remainder operation are shown in + the following table. Although the other rounding modes can be used, they may not give + useful results. +
+
+ + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0 + The remainder is positive if the dividend is negative, otherwise it is negative. +
ROUND_DOWN1 + The remainder has the same sign as the dividend.
+ This uses 'truncating division' and matches the behaviour of JavaScript's + remainder operator %. +
ROUND_FLOOR3 + The remainder has the same sign as the divisor.
+ This matches Python's % operator. +
ROUND_HALF_EVEN6The IEEE 754 remainder function.
EUCLID9 + The remainder is always positive. Euclidian division:
+ q = sign(n) * floor(a / abs(n)) +
+
+
+ The rounding/modulo modes are available as enumerated properties of the BigNumber + constructor. +
+
See modulo.
+
+
BigNumber.config({ MODULO_MODE: BigNumber.EUCLID })
+BigNumber.config({ MODULO_MODE: 9 })          // equivalent
+
+ + + +
POW_PRECISION
+
+ number: integer, 0 to 1e+9 inclusive.
+ Default value: 0 +
+
+ The maximum precision, i.e. number of significant digits, of the result of the power + operation (unless a modulus is specified). +
+
If set to 0, the number of significant digits will not be limited.
+
See exponentiatedBy.
+
BigNumber.config({ POW_PRECISION: 100 })
+ + + +
FORMAT
+
object
+
+ The FORMAT object configures the format of the string returned by the + toFormat method. +
+
+ The example below shows the properties of the FORMAT object that are + recognised, and their default values. +
+
+ Unlike the other configuration properties, the values of the properties of the + FORMAT object will not be checked for validity. The existing + FORMAT object will simply be replaced by the object that is passed in. + The object can include any number of the properties shown below. +
+
See toFormat for examples of usage.
+
+
+BigNumber.config({
+  FORMAT: {
+    // string to prepend
+    prefix: '',
+    // decimal separator
+    decimalSeparator: '.',
+    // grouping separator of the integer part
+    groupSeparator: ',',
+    // primary grouping size of the integer part
+    groupSize: 3,
+    // secondary grouping size of the integer part
+    secondaryGroupSize: 0,
+    // grouping separator of the fraction part
+    fractionGroupSeparator: ' ',
+    // grouping size of the fraction part
+    fractionGroupSize: 0,
+    // string to append
+    suffix: ''
+  }
+});
+
+ + + +
ALPHABET
+
+ string
+ Default value: '0123456789abcdefghijklmnopqrstuvwxyz' +
+
+ The alphabet used for base conversion. The length of the alphabet corresponds to the + maximum value of the base argument that can be passed to the + BigNumber constructor or + toString. +
+
+ There is no maximum length for the alphabet, but it must be at least 2 characters long, and + it must not contain whitespace or a repeated character, or the sign indicators + '+' and '-', or the decimal separator '.'. +
+
+
// duodecimal (base 12)
+BigNumber.config({ ALPHABET: '0123456789TE' })
+x = new BigNumber('T', 12)
+x.toString()                // '10'
+x.toString(12)              // 'T'
+
+ + + +
+

+

Returns an object with the above properties and their current values.

+

+ Throws if object is not an object, or if an invalid value is assigned to + one or more of the above properties. See Errors. +

+
+BigNumber.config({
+  DECIMAL_PLACES: 40,
+  ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL,
+  EXPONENTIAL_AT: [-10, 20],
+  RANGE: [-500, 500],
+  CRYPTO: true,
+  MODULO_MODE: BigNumber.ROUND_FLOOR,
+  POW_PRECISION: 80,
+  FORMAT: {
+    groupSize: 3,
+    groupSeparator: ' ',
+    decimalSeparator: ','
+  },
+  ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
+});
+
+obj = BigNumber.config();
+obj.DECIMAL_PLACES        // 40
+obj.RANGE                 // [-500, 500]
+ + + +
+ isBigNumber.isBigNumber(value) ⇒ boolean +
+

value: any

+

+ Returns true if value is a BigNumber instance, otherwise returns + false. +

+
x = 42
+y = new BigNumber(x)
+
+BigNumber.isBigNumber(x)             // false
+y instanceof BigNumber               // true
+BigNumber.isBigNumber(y)             // true
+
+BN = BigNumber.clone();
+z = new BN(x)
+z instanceof BigNumber               // false
+BigNumber.isBigNumber(z)             // true
+

+ If value is a BigNumber instance and BigNumber.DEBUG is true, + then this method will also check if value is well-formed, and throw if it is not. + See Errors. +

+

+ The check can be useful if creating a BigNumber from an object literal. + See BigNumber. +

+
+x = new BigNumber(10)
+
+// Change x.c to an illegitimate value.
+x.c = NaN
+
+BigNumber.DEBUG = false
+
+// No error.
+BigNumber.isBigNumber(x)    // true
+
+BigNumber.DEBUG = true
+
+// Error.
+BigNumber.isBigNumber(x)    // '[BigNumber Error] Invalid BigNumber'
+ + + +
maximum.max(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the maximum of the arguments. +

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.maximum(4e9, x, '123456789.9')      // '4000000000'
+
+arr = [12, '13', new BigNumber(14)]
+BigNumber.max.apply(null, arr)                // '14'
+ + + +
minimum.min(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the minimum of the arguments. +

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.minimum(4e9, x, '123456789.9')      // '123456789.9'
+
+arr = [2, new BigNumber(-14), '-15.9999', -12]
+BigNumber.min.apply(null, arr)                // '-15.9999'
+ + + +
+ random.random([dp]) ⇒ BigNumber +
+

dp: number: integer, 0 to 1e+9 inclusive

+

+ Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and + less than 1. +

+

+ The return value will have dp decimal places (or less if trailing zeros are + produced).
+ If dp is omitted then the number of decimal places will default to the current + DECIMAL_PLACES setting. +

+

+ Depending on the value of this BigNumber constructor's + CRYPTO setting and the support for the + crypto object in the host environment, the random digits of the return value are + generated by either Math.random (fastest), crypto.getRandomValues + (Web Cryptography API in recent browsers) or crypto.randomBytes (Node.js). +

+

+ To be able to set CRYPTO to true when using + Node.js, the crypto object must be available globally: +

+
// Node.js
+const crypto = require('crypto');   // CommonJS
+import * as crypto from 'crypto';   // ES module
+global.crypto = crypto;
+

+ If CRYPTO is true, i.e. one of the + crypto methods is to be used, the value of a returned BigNumber should be + cryptographically-secure and statistically indistinguishable from a random value. +

+

+ Throws if dp is invalid. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 10 })
+BigNumber.random()              // '0.4117936847'
+BigNumber.random(20)            // '0.78193327636914089009'
+ + + +
sum.sum(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the sum of the arguments.

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.sum(4e9, x, '123456789.9')      // '7381326134.9378653'
+
+arr = [2, new BigNumber(14), '15.9999', 12]
+BigNumber.sum.apply(null, arr)            // '43.9999'
+ + + +

Properties

+

+ The library's enumerated rounding modes are stored as properties of the constructor.
+ (They are not referenced internally by the library itself.) +

+

+ Rounding modes 0 to 6 (inclusive) are the same as those of Java's + BigDecimal class. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0Rounds away from zero
ROUND_DOWN1Rounds towards zero
ROUND_CEIL2Rounds towards Infinity
ROUND_FLOOR3Rounds towards -Infinity
ROUND_HALF_UP4 + Rounds towards nearest neighbour.
+ If equidistant, rounds away from zero +
ROUND_HALF_DOWN5 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards zero +
ROUND_HALF_EVEN6 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards even neighbour +
ROUND_HALF_CEIL7 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards Infinity +
ROUND_HALF_FLOOR8 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards -Infinity +
+
+BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL })
+BigNumber.config({ ROUNDING_MODE: 2 })     // equivalent
+ +
DEBUG
+

undefined|false|true

+

+ If BigNumber.DEBUG is set true then an error will be thrown + if this BigNumber constructor receives an invalid value, such as + a value of type number with more than 15 significant digits. + See BigNumber. +

+

+ An error will also be thrown if the isBigNumber + method receives a BigNumber that is not well-formed. + See isBigNumber. +

+
BigNumber.DEBUG = true
+ + +

INSTANCE

+ + +

Methods

+

The methods inherited by a BigNumber instance from its constructor's prototype object.

+

A BigNumber is immutable in the sense that it is not changed by its methods.

+

+ The treatment of ±0, ±Infinity and NaN is + consistent with how JavaScript treats these values. +

+

Many method names have a shorter alias.

+ + + +
absoluteValue.abs() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of + this BigNumber. +

+

The return value is always exact and unrounded.

+
+x = new BigNumber(-0.8)
+y = x.absoluteValue()           // '0.8'
+z = y.abs()                     // '0.8'
+ + + +
+ comparedTo.comparedTo(n [, base]) ⇒ number +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+ + + + + + + + + + + + + + + + + + +
Returns 
1If the value of this BigNumber is greater than the value of n
-1If the value of this BigNumber is less than the value of n
0If this BigNumber and n have the same value
nullIf the value of either this BigNumber or n is NaN
+
+x = new BigNumber(Infinity)
+y = new BigNumber(5)
+x.comparedTo(y)                 // 1
+x.comparedTo(x.minus(1))        // 0
+y.comparedTo(NaN)               // null
+y.comparedTo('110', 2)          // -1
+ + + +
+ decimalPlaces.dp([dp [, rm]]) ⇒ BigNumber|number +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ If dp is a number, returns a BigNumber whose value is the value of this BigNumber + rounded by rounding mode rm to a maximum of dp decimal places. +

+

+ If dp is omitted, or is null or undefined, the return + value is the number of decimal places of the value of this BigNumber, or null if + the value of this BigNumber is ±Infinity or NaN. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = new BigNumber(1234.56)
+x.decimalPlaces(1)                     // '1234.6'
+x.dp()                                 // 2
+x.decimalPlaces(2)                     // '1234.56'
+x.dp(10)                               // '1234.56'
+x.decimalPlaces(0, 1)                  // '1234'
+x.dp(0, 6)                             // '1235'
+x.decimalPlaces(1, 1)                  // '1234.5'
+x.dp(1, BigNumber.ROUND_HALF_EVEN)     // '1234.6'
+x                                      // '1234.56'
+y = new BigNumber('9.9e-101')
+y.dp()                                 // 102
+ + + +
dividedBy.div(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber divided by + n, rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+
+x = new BigNumber(355)
+y = new BigNumber(113)
+x.dividedBy(y)                  // '3.14159292035398230088'
+x.div(5)                        // '71'
+x.div(47, 16)                   // '5'
+ + + +
+ dividedToIntegerBy.idiv(n [, base]) ⇒ + BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + n. +

+
+x = new BigNumber(5)
+y = new BigNumber(3)
+x.dividedToIntegerBy(y)         // '1'
+x.idiv(0.7)                     // '7'
+x.idiv('0.f', 16)               // '5'
+ + + +
+ exponentiatedBy.pow(n [, m]) ⇒ BigNumber +
+

+ n: number|string|BigNumber: integer
+ m: number|string|BigNumber +

+

+ Returns a BigNumber whose value is the value of this BigNumber exponentiated by + n, i.e. raised to the power n, and optionally modulo a modulus + m. +

+

+ Throws if n is not an integer. See Errors. +

+

+ If n is negative the result is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ As the number of digits of the result of the power operation can grow so large so quickly, + e.g. 123.45610000 has over 50000 digits, the number of significant + digits calculated is limited to the value of the + POW_PRECISION setting (unless a modulus + m is specified). +

+

+ By default POW_PRECISION is set to 0. + This means that an unlimited number of significant digits will be calculated, and that the + method's performance will decrease dramatically for larger exponents. +

+

+ If m is specified and the value of m, n and this + BigNumber are integers, and n is positive, then a fast modular exponentiation + algorithm is used, otherwise the operation will be performed as + x.exponentiatedBy(n).modulo(m) with a + POW_PRECISION of 0. +

+
+Math.pow(0.7, 2)                // 0.48999999999999994
+x = new BigNumber(0.7)
+x.exponentiatedBy(2)            // '0.49'
+BigNumber(3).pow(-2)            // '0.11111111111111111111'
+ + + +
+ integerValue.integerValue([rm]) ⇒ BigNumber +
+

+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + rounding mode rm. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if rm is invalid. See Errors. +

+
+x = new BigNumber(123.456)
+x.integerValue()                        // '123'
+x.integerValue(BigNumber.ROUND_CEIL)    // '124'
+y = new BigNumber(-12.7)
+y.integerValue()                        // '-13'
+y.integerValue(BigNumber.ROUND_DOWN)    // '-12'
+

+ The following is an example of how to add a prototype method that emulates JavaScript's + Math.round function. Math.ceil, Math.floor and + Math.trunc can be emulated in the same way with + BigNumber.ROUND_CEIL, BigNumber.ROUND_FLOOR and + BigNumber.ROUND_DOWN respectively. +

+
+BigNumber.prototype.round = function () {
+  return this.integerValue(BigNumber.ROUND_HALF_CEIL);
+};
+x.round()                               // '123'
+ + + +
isEqualTo.eq(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is equal to the value of + n, otherwise returns false.
+ As with JavaScript, NaN does not equal NaN. +

+

Note: This method uses the comparedTo method internally.

+
+0 === 1e-324                    // true
+x = new BigNumber(0)
+x.isEqualTo('1e-324')           // false
+BigNumber(-0).eq(x)             // true  ( -0 === 0 )
+BigNumber(255).eq('ff', 16)     // true
+
+y = new BigNumber(NaN)
+y.isEqualTo(NaN)                // false
+ + + +
isFinite.isFinite() ⇒ boolean
+

+ Returns true if the value of this BigNumber is a finite number, otherwise + returns false. +

+

+ The only possible non-finite values of a BigNumber are NaN, Infinity + and -Infinity. +

+
+x = new BigNumber(1)
+x.isFinite()                    // true
+y = new BigNumber(Infinity)
+y.isFinite()                    // false
+

+ Note: The native method isFinite() can be used if + n <= Number.MAX_VALUE. +

+ + + +
isGreaterThan.gt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 > (0.3 - 0.2)                             // true
+x = new BigNumber(0.1)
+x.isGreaterThan(BigNumber(0.3).minus(0.2))    // false
+BigNumber(0).gt(x)                            // false
+BigNumber(11, 3).gt(11.1, 2)                  // true
+ + + +
+ isGreaterThanOrEqualTo.gte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than or equal to the value + of n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) >= 0.1                     // false
+x = new BigNumber(0.3).minus(0.2)
+x.isGreaterThanOrEqualTo(0.1)          // true
+BigNumber(1).gte(x)                    // true
+BigNumber(10, 18).gte('i', 36)         // true
+ + + +
isInteger.isInteger() ⇒ boolean
+

+ Returns true if the value of this BigNumber is an integer, otherwise returns + false. +

+
+x = new BigNumber(1)
+x.isInteger()                   // true
+y = new BigNumber(123.456)
+y.isInteger()                   // false
+ + + +
isLessThan.lt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) < 0.1                       // true
+x = new BigNumber(0.3).minus(0.2)
+x.isLessThan(0.1)                       // false
+BigNumber(0).lt(x)                      // true
+BigNumber(11.1, 2).lt(11, 3)            // true
+ + + +
+ isLessThanOrEqualTo.lte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than or equal to the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 <= (0.3 - 0.2)                                // false
+x = new BigNumber(0.1)
+x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2))  // true
+BigNumber(-1).lte(x)                              // true
+BigNumber(10, 18).lte('i', 36)                    // true
+ + + +
isNaN.isNaN() ⇒ boolean
+

+ Returns true if the value of this BigNumber is NaN, otherwise + returns false. +

+
+x = new BigNumber(NaN)
+x.isNaN()                       // true
+y = new BigNumber('Infinity')
+y.isNaN()                       // false
+

Note: The native method isNaN() can also be used.

+ + + +
isNegative.isNegative() ⇒ boolean
+

+ Returns true if the sign of this BigNumber is negative, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isNegative()                  // true
+y = new BigNumber(2)
+y.isNegative()                  // false
+

Note: n < 0 can be used if n <= -Number.MIN_VALUE.

+ + + +
isPositive.isPositive() ⇒ boolean
+

+ Returns true if the sign of this BigNumber is positive, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isPositive()                  // false
+y = new BigNumber(2)
+y.isPositive()                  // true
+ + + +
isZero.isZero() ⇒ boolean
+

+ Returns true if the value of this BigNumber is zero or minus zero, otherwise + returns false. +

+
+x = new BigNumber(-0)
+x.isZero() && x.isNegative()         // true
+y = new BigNumber(Infinity)
+y.isZero()                      // false
+

Note: n == 0 can be used if n >= Number.MIN_VALUE.

+ + + +
+ minus.minus(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber minus n.

+

The return value is always exact and unrounded.

+
+0.3 - 0.1                       // 0.19999999999999998
+x = new BigNumber(0.3)
+x.minus(0.1)                    // '0.2'
+x.minus(0.6, 20)                // '0'
+ + + +
modulo.mod(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber modulo n, i.e. + the integer remainder of dividing this BigNumber by n. +

+

+ The value returned, and in particular its sign, is dependent on the value of the + MODULO_MODE setting of this BigNumber constructor. + If it is 1 (default value), the result will have the same sign as this BigNumber, + and it will match that of Javascript's % operator (within the limits of double + precision) and BigDecimal's remainder method. +

+

The return value is always exact and unrounded.

+

+ See MODULO_MODE for a description of the other + modulo modes. +

+
+1 % 0.9                         // 0.09999999999999998
+x = new BigNumber(1)
+x.modulo(0.9)                   // '0.1'
+y = new BigNumber(33)
+y.mod('a', 33)                  // '3'
+ + + +
+ multipliedBy.times(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber multiplied by n. +

+

The return value is always exact and unrounded.

+
+0.6 * 3                         // 1.7999999999999998
+x = new BigNumber(0.6)
+y = x.multipliedBy(3)           // '1.8'
+BigNumber('7e+500').times(y)    // '1.26e+501'
+x.multipliedBy('-a', 16)        // '-6'
+ + + +
negated.negated() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by + -1. +

+
+x = new BigNumber(1.8)
+x.negated()                     // '-1.8'
+y = new BigNumber(-1.3)
+y.negated()                     // '1.3'
+ + + +
plus.plus(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber plus n.

+

The return value is always exact and unrounded.

+
+0.1 + 0.2                       // 0.30000000000000004
+x = new BigNumber(0.1)
+y = x.plus(0.2)                 // '0.3'
+BigNumber(0.7).plus(x).plus(y)  // '1.1'
+x.plus('0.1', 8)                // '0.225'
+ + + +
+ precision.sd([d [, rm]]) ⇒ BigNumber|number +
+

+ d: number|boolean: integer, 1 to 1e+9 + inclusive, or true or false
+ rm: number: integer, 0 to 8 inclusive. +

+

+ If d is a number, returns a BigNumber whose value is the value of this BigNumber + rounded to a precision of d significant digits using rounding mode + rm. +

+

+ If d is omitted or is null or undefined, the return + value is the number of significant digits of the value of this BigNumber, or null + if the value of this BigNumber is ±Infinity or NaN. +

+

+ If d is true then any trailing zeros of the integer + part of a number are counted as significant digits, otherwise they are not. +

+

+ If rm is omitted or is null or undefined, + ROUNDING_MODE will be used. +

+

+ Throws if d or rm is invalid. See Errors. +

+
+x = new BigNumber(9876.54321)
+x.precision(6)                         // '9876.54'
+x.sd()                                 // 9
+x.precision(6, BigNumber.ROUND_UP)     // '9876.55'
+x.sd(2)                                // '9900'
+x.precision(2, 1)                      // '9800'
+x                                      // '9876.54321'
+y = new BigNumber(987000)
+y.precision()                          // 3
+y.sd(true)                             // 6
+ + + +
shiftedBy.shiftedBy(n) ⇒ BigNumber
+

+ n: number: integer, + -9007199254740991 to 9007199254740991 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber shifted by n + places. +

+ The shift is of the decimal point, i.e. of powers of ten, and is to the left if n + is negative or to the right if n is positive. +

+

The return value is always exact and unrounded.

+

+ Throws if n is invalid. See Errors. +

+
+x = new BigNumber(1.23)
+x.shiftedBy(3)                      // '1230'
+x.shiftedBy(-3)                     // '0.00123'
+ + + +
squareRoot.sqrt() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the square root of the value of this BigNumber, + rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ The return value will be correctly rounded, i.e. rounded as if the result was first calculated + to an infinite number of correct digits before rounding. +

+
+x = new BigNumber(16)
+x.squareRoot()                  // '4'
+y = new BigNumber(3)
+y.sqrt()                        // '1.73205080756887729353'
+ + + +
+ toExponential.toExponential([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in exponential notation rounded + using rounding mode rm to dp decimal places, i.e with one digit + before the decimal point and dp digits after it. +

+

+ If the value of this BigNumber in exponential notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ If dp is omitted, or is null or undefined, the number + of digits after the decimal point defaults to the minimum number of digits necessary to + represent the value exactly.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toExponential()               // '4.56e+1'
+y.toExponential()               // '4.56e+1'
+x.toExponential(0)              // '5e+1'
+y.toExponential(0)              // '5e+1'
+x.toExponential(1)              // '4.6e+1'
+y.toExponential(1)              // '4.6e+1'
+y.toExponential(1, 1)           // '4.5e+1'  (ROUND_DOWN)
+x.toExponential(3)              // '4.560e+1'
+y.toExponential(3)              // '4.560e+1'
+ + + +
+ toFixed.toFixed([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm. +

+

+ If the value of this BigNumber in normal notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ Unlike Number.prototype.toFixed, which returns exponential notation if a number + is greater or equal to 1021, this method will always return normal + notation. +

+

+ If dp is omitted or is null or undefined, the return + value will be unrounded and in normal notation. This is also unlike + Number.prototype.toFixed, which returns the value to zero decimal places.
+ It is useful when fixed-point notation is required and the current + EXPONENTIAL_AT setting causes + toString to return exponential notation.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 3.456
+y = new BigNumber(x)
+x.toFixed()                     // '3'
+y.toFixed()                     // '3.456'
+y.toFixed(0)                    // '3'
+x.toFixed(2)                    // '3.46'
+y.toFixed(2)                    // '3.46'
+y.toFixed(2, 1)                 // '3.45'  (ROUND_DOWN)
+x.toFixed(5)                    // '3.45600'
+y.toFixed(5)                    // '3.45600'
+ + + +
+ toFormat.toFormat([dp [, rm[, format]]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive
+ format: object: see FORMAT +

+

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm, and formatted + according to the properties of the format object. +

+

+ See FORMAT and the examples below for the properties of the + format object, their types, and their usage. A formatting object may contain + some or all of the recognised properties. +

+

+ If dp is omitted or is null or undefined, then the + return value is not rounded to a fixed number of decimal places.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used.
+ If format is omitted or is null or undefined, the + FORMAT object is used. +

+

+ Throws if dp, rm or format is invalid. See + Errors. +

+
+fmt = {
+  prefix: '',
+  decimalSeparator: '.',
+  groupSeparator: ',',
+  groupSize: 3,
+  secondaryGroupSize: 0,
+  fractionGroupSeparator: ' ',
+  fractionGroupSize: 0,
+  suffix: ''
+}
+
+x = new BigNumber('123456789.123456789')
+
+// Set the global formatting options
+BigNumber.config({ FORMAT: fmt })
+
+x.toFormat()                              // '123,456,789.123456789'
+x.toFormat(3)                             // '123,456,789.123'
+
+// If a reference to the object assigned to FORMAT has been retained,
+// the format properties can be changed directly
+fmt.groupSeparator = ' '
+fmt.fractionGroupSize = 5
+x.toFormat()                              // '123 456 789.12345 6789'
+
+// Alternatively, pass the formatting options as an argument
+fmt = {
+  prefix: '=> ',
+  decimalSeparator: ',',
+  groupSeparator: '.',
+  groupSize: 3,
+  secondaryGroupSize: 2
+}
+
+x.toFormat()                              // '123 456 789.12345 6789'
+x.toFormat(fmt)                           // '=> 12.34.56.789,123456789'
+x.toFormat(2, fmt)                        // '=> 12.34.56.789,12'
+x.toFormat(3, BigNumber.ROUND_UP, fmt)    // '=> 12.34.56.789,124'
+ + + +
+ toFraction.toFraction([maximum_denominator]) + ⇒ [BigNumber, BigNumber] +
+

+ maximum_denominator: + number|string|BigNumber: integer >= 1 and <= + Infinity +

+

+ Returns 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 maximum_denominator. +

+

+ If a maximum_denominator is not specified, or is null or + undefined, the denominator will be the lowest value necessary to represent the + number exactly. +

+

+ Throws if maximum_denominator is invalid. See Errors. +

+
+x = new BigNumber(1.75)
+x.toFraction()                  // '7, 4'
+
+pi = new BigNumber('3.14159265358')
+pi.toFraction()                 // '157079632679,50000000000'
+pi.toFraction(100000)           // '312689, 99532'
+pi.toFraction(10000)            // '355, 113'
+pi.toFraction(100)              // '311, 99'
+pi.toFraction(10)               // '22, 7'
+pi.toFraction(1)                // '3, 1'
+ + + +
toJSON.toJSON() ⇒ string
+

As valueOf.

+
+x = new BigNumber('177.7e+457')
+y = new BigNumber(235.4325)
+z = new BigNumber('0.0098074')
+
+// Serialize an array of three BigNumbers
+str = JSON.stringify( [x, y, z] )
+// "["1.777e+459","235.4325","0.0098074"]"
+
+// Return an array of three BigNumbers
+JSON.parse(str, function (key, val) {
+    return key === '' ? val : new BigNumber(val)
+})
+ + + +
toNumber.toNumber() ⇒ number
+

Returns the value of this BigNumber as a JavaScript number primitive.

+

+ This method is identical to using type coercion with the unary plus operator. +

+
+x = new BigNumber(456.789)
+x.toNumber()                    // 456.789
++x                              // 456.789
+
+y = new BigNumber('45987349857634085409857349856430985')
+y.toNumber()                    // 4.598734985763409e+34
+
+z = new BigNumber(-0)
+1 / z.toNumber()                // -Infinity
+1 / +z                          // -Infinity
+ + + +
+ toPrecision.toPrecision([sd [, rm]]) ⇒ string +
+

+ sd: number: integer, 1 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber rounded to sd + significant digits using rounding mode rm. +

+

+ If sd is less than the number of digits necessary to represent the integer part + of the value in normal (fixed-point) notation, then exponential notation is used. +

+

+ If sd is omitted, or is null or undefined, then the + return value is the same as n.toString().
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if sd or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toPrecision()                 // '45.6'
+y.toPrecision()                 // '45.6'
+x.toPrecision(1)                // '5e+1'
+y.toPrecision(1)                // '5e+1'
+y.toPrecision(2, 0)             // '4.6e+1'  (ROUND_UP)
+y.toPrecision(2, 1)             // '4.5e+1'  (ROUND_DOWN)
+x.toPrecision(5)                // '45.600'
+y.toPrecision(5)                // '45.600'
+ + + +
toString.toString([base]) ⇒ string
+

+ base: number: integer, 2 to ALPHABET.length + inclusive (see ALPHABET). +

+

+ Returns a string representing the value of this BigNumber in the specified base, or base + 10 if base is omitted or is null or + undefined. +

+

+ For bases above 10, and using the default base conversion alphabet + (see ALPHABET), values from 10 to + 35 are represented by a-z + (as with Number.prototype.toString). +

+

+ If a base is specified the value is rounded according to the current + DECIMAL_PLACES + and ROUNDING_MODE settings. +

+

+ If a base is not specified, and this BigNumber has a positive + exponent that is equal to or greater than the positive component of the + current EXPONENTIAL_AT setting, + or a negative exponent equal to or less than the negative component of the + setting, then exponential notation is returned. +

+

If base is null or undefined it is ignored.

+

+ Throws if base is invalid. See Errors. +

+
+x = new BigNumber(750000)
+x.toString()                    // '750000'
+BigNumber.config({ EXPONENTIAL_AT: 5 })
+x.toString()                    // '7.5e+5'
+
+y = new BigNumber(362.875)
+y.toString(2)                   // '101101010.111'
+y.toString(9)                   // '442.77777777777777777778'
+y.toString(32)                  // 'ba.s'
+
+BigNumber.config({ DECIMAL_PLACES: 4 });
+z = new BigNumber('1.23456789')
+z.toString()                    // '1.23456789'
+z.toString(10)                  // '1.2346'
+ + + +
valueOf.valueOf() ⇒ string
+

+ As toString, but does not accept a base argument and includes + the minus sign for negative zero. +

+
+x = new BigNumber('-0')
+x.toString()                    // '0'
+x.valueOf()                     // '-0'
+y = new BigNumber('1.777e+457')
+y.valueOf()                     // '1.777e+457'
+ + + +

Properties

+

The properties of a BigNumber instance:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescriptionTypeValue
ccoefficient*number[] Array of base 1e14 numbers
eexponentnumberInteger, -1000000000 to 1000000000 inclusive
ssignnumber-1 or 1
+

*significand

+

+ The value of any of the c, e and s properties may also + be null. +

+

+ The above properties are best considered to be read-only. In early versions of this library it + was okay to change the exponent of a BigNumber by writing to its exponent property directly, + but this is no longer reliable as the value of the first element of the coefficient array is + now dependent on the exponent. +

+

+ Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are + not necessarily preserved. +

+
x = new BigNumber(0.123)              // '0.123'
+x.toExponential()                     // '1.23e-1'
+x.c                                   // '1,2,3'
+x.e                                   // -1
+x.s                                   // 1
+
+y = new Number(-123.4567000e+2)       // '-12345.67'
+y.toExponential()                     // '-1.234567e+4'
+z = new BigNumber('-123.4567000e+2')  // '-12345.67'
+z.toExponential()                     // '-1.234567e+4'
+z.c                                   // '1,2,3,4,5,6,7'
+z.e                                   // 4
+z.s                                   // -1
+ + + +

Zero, NaN and Infinity

+

+ The table below shows how ±0, NaN and + ±Infinity are stored. +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
ces
±0[0]0±1
NaNnullnullnull
±Infinitynullnull±1
+
+x = new Number(-0)              // 0
+1 / x == -Infinity              // true
+
+y = new BigNumber(-0)           // '0'
+y.c                             // '0' ( [0].toString() )
+y.e                             // 0
+y.s                             // -1
+ + + +

Errors

+

The table below shows the errors that are thrown.

+

+ The errors are generic Error objects whose message begins + '[BigNumber Error]'. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodThrows
+ BigNumber
+ comparedTo
+ dividedBy
+ dividedToIntegerBy
+ isEqualTo
+ isGreaterThan
+ isGreaterThanOrEqualTo
+ isLessThan
+ isLessThanOrEqualTo
+ minus
+ modulo
+ plus
+ multipliedBy +
Base not a primitive number
Base not an integer
Base out of range
Number primitive has more than 15 significant digits*
Not a base... number*
Not a number*
cloneObject expected
configObject expected
DECIMAL_PLACES not a primitive number
DECIMAL_PLACES not an integer
DECIMAL_PLACES out of range
ROUNDING_MODE not a primitive number
ROUNDING_MODE not an integer
ROUNDING_MODE out of range
EXPONENTIAL_AT not a primitive number
EXPONENTIAL_AT not an integer
EXPONENTIAL_AT out of range
RANGE not a primitive number
RANGE not an integer
RANGE cannot be zero
RANGE cannot be zero
CRYPTO not true or false
crypto unavailable
MODULO_MODE not a primitive number
MODULO_MODE not an integer
MODULO_MODE out of range
POW_PRECISION not a primitive number
POW_PRECISION not an integer
POW_PRECISION out of range
FORMAT not an object
ALPHABET invalid
+ decimalPlaces
+ precision
+ random
+ shiftedBy
+ toExponential
+ toFixed
+ toFormat
+ toPrecision +
Argument not a primitive number
Argument not an integer
Argument out of range
+ decimalPlaces
+ precision +
Argument not true or false
exponentiatedByArgument not an integer
isBigNumberInvalid BigNumber*
+ minimum
+ maximum +
Not a number*
+ random + crypto unavailable
+ toFormat + Argument not an object
toFractionArgument not an integer
Argument out of range
toStringBase not a primitive number
Base not an integer
Base out of range
+

*Only thrown if BigNumber.DEBUG is true.

+

To determine if an exception is a BigNumber Error:

+
+try {
+  // ...
+} catch (e) {
+  if (e instanceof Error && e.message.indexOf('[BigNumber Error]') === 0) {
+      // ...
+  }
+}
+ + + +

Type coercion

+

+ To prevent the accidental use of a BigNumber in primitive number operations, or the + accidental addition of a BigNumber to a string, the valueOf method can be safely + overwritten as shown below. +

+

+ The valueOf method is the same as the + toJSON method, and both are the same as the + toString method except they do not take a base + argument and they include the minus sign for negative zero. +

+
+BigNumber.prototype.valueOf = function () {
+  throw Error('valueOf called!')
+}
+
+x = new BigNumber(1)
+x / 2                    // '[BigNumber Error] valueOf called!'
+x + 'abc'                // '[BigNumber Error] valueOf called!'
+
+ + + +

FAQ

+ +
Why are trailing fractional zeros removed from BigNumbers?
+

+ Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the + precision of a value. This can be useful but the results of arithmetic operations can be + misleading. +

+
+x = new BigDecimal("1.0")
+y = new BigDecimal("1.1000")
+z = x.add(y)                      // 2.1000
+
+x = new BigDecimal("1.20")
+y = new BigDecimal("3.45000")
+z = x.multiply(y)                 // 4.1400000
+

+ To specify the precision of a value is to specify that the value lies + within a certain range. +

+

+ In the first example, x has a value of 1.0. The trailing zero shows + the precision of the value, implying that it is in the range 0.95 to + 1.05. Similarly, the precision indicated by the trailing zeros of y + indicates that the value is in the range 1.09995 to 1.10005. +

+

+ If we add the two lowest values in the ranges we have, 0.95 + 1.09995 = 2.04995, + and if we add the two highest values we have, 1.05 + 1.10005 = 2.15005, so the + range of the result of the addition implied by the precision of its operands is + 2.04995 to 2.15005. +

+

+ The result given by BigDecimal of 2.1000 however, indicates that the value is in + the range 2.09995 to 2.10005 and therefore the precision implied by + its trailing zeros may be misleading. +

+

+ In the second example, the true range is 4.122744 to 4.157256 yet + the BigDecimal answer of 4.1400000 indicates a range of 4.13999995 + to 4.14000005. Again, the precision implied by the trailing zeros may be + misleading. +

+

+ This library, like binary floating point and most calculators, does not retain trailing + fractional zeros. Instead, the toExponential, toFixed and + toPrecision methods enable trailing zeros to be added if and when required.
+

+
+ + + diff --git a/node_modules/bignumber.js/package.json b/node_modules/bignumber.js/package.json new file mode 100644 index 0000000..e0571a0 --- /dev/null +++ b/node_modules/bignumber.js/package.json @@ -0,0 +1,50 @@ +{ + "name": "bignumber.js", + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic", + "version": "9.1.2", + "keywords": [ + "arbitrary", + "precision", + "arithmetic", + "big", + "number", + "decimal", + "float", + "biginteger", + "bigdecimal", + "bignumber", + "bigint", + "bignum" + ], + "repository": { + "type": "git", + "url": "https://github.com/MikeMcl/bignumber.js.git" + }, + "main": "bignumber", + "module": "bignumber.mjs", + "browser": "bignumber.js", + "types": "bignumber.d.ts", + "exports": { + ".": { + "types": "./bignumber.d.ts", + "require": "./bignumber.js", + "import": "./bignumber.mjs", + "browser": "./bignumber.js" + }, + "./bignumber.mjs": "./bignumber.mjs", + "./bignumber.js": "./bignumber.js", + "./package.json": "./package.json" + }, + "author": { + "name": "Michael Mclaughlin", + "email": "M8ch88l@gmail.com" + }, + "engines": { + "node": "*" + }, + "license": "MIT", + "scripts": { + "test": "node test/test" + }, + "dependencies": {} +} diff --git a/node_modules/binary-extensions/binary-extensions.json b/node_modules/binary-extensions/binary-extensions.json new file mode 100644 index 0000000..ac08048 --- /dev/null +++ b/node_modules/binary-extensions/binary-extensions.json @@ -0,0 +1,263 @@ +[ + "3dm", + "3ds", + "3g2", + "3gp", + "7z", + "a", + "aac", + "adp", + "afdesign", + "afphoto", + "afpub", + "ai", + "aif", + "aiff", + "alz", + "ape", + "apk", + "appimage", + "ar", + "arj", + "asf", + "au", + "avi", + "bak", + "baml", + "bh", + "bin", + "bk", + "bmp", + "btif", + "bz2", + "bzip2", + "cab", + "caf", + "cgm", + "class", + "cmx", + "cpio", + "cr2", + "cur", + "dat", + "dcm", + "deb", + "dex", + "djvu", + "dll", + "dmg", + "dng", + "doc", + "docm", + "docx", + "dot", + "dotm", + "dra", + "DS_Store", + "dsk", + "dts", + "dtshd", + "dvb", + "dwg", + "dxf", + "ecelp4800", + "ecelp7470", + "ecelp9600", + "egg", + "eol", + "eot", + "epub", + "exe", + "f4v", + "fbs", + "fh", + "fla", + "flac", + "flatpak", + "fli", + "flv", + "fpx", + "fst", + "fvt", + "g3", + "gh", + "gif", + "graffle", + "gz", + "gzip", + "h261", + "h263", + "h264", + "icns", + "ico", + "ief", + "img", + "ipa", + "iso", + "jar", + "jpeg", + "jpg", + "jpgv", + "jpm", + "jxr", + "key", + "ktx", + "lha", + "lib", + "lvp", + "lz", + "lzh", + "lzma", + "lzo", + "m3u", + "m4a", + "m4v", + "mar", + "mdi", + "mht", + "mid", + "midi", + "mj2", + "mka", + "mkv", + "mmr", + "mng", + "mobi", + "mov", + "movie", + "mp3", + "mp4", + "mp4a", + "mpeg", + "mpg", + "mpga", + "mxu", + "nef", + "npx", + "numbers", + "nupkg", + "o", + "odp", + "ods", + "odt", + "oga", + "ogg", + "ogv", + "otf", + "ott", + "pages", + "pbm", + "pcx", + "pdb", + "pdf", + "pea", + "pgm", + "pic", + "png", + "pnm", + "pot", + "potm", + "potx", + "ppa", + "ppam", + "ppm", + "pps", + "ppsm", + "ppsx", + "ppt", + "pptm", + "pptx", + "psd", + "pya", + "pyc", + "pyo", + "pyv", + "qt", + "rar", + "ras", + "raw", + "resources", + "rgb", + "rip", + "rlc", + "rmf", + "rmvb", + "rpm", + "rtf", + "rz", + "s3m", + "s7z", + "scpt", + "sgi", + "shar", + "snap", + "sil", + "sketch", + "slk", + "smv", + "snk", + "so", + "stl", + "suo", + "sub", + "swf", + "tar", + "tbz", + "tbz2", + "tga", + "tgz", + "thmx", + "tif", + "tiff", + "tlz", + "ttc", + "ttf", + "txz", + "udf", + "uvh", + "uvi", + "uvm", + "uvp", + "uvs", + "uvu", + "viv", + "vob", + "war", + "wav", + "wax", + "wbmp", + "wdp", + "weba", + "webm", + "webp", + "whl", + "wim", + "wm", + "wma", + "wmv", + "wmx", + "woff", + "woff2", + "wrm", + "wvx", + "xbm", + "xif", + "xla", + "xlam", + "xls", + "xlsb", + "xlsm", + "xlsx", + "xlt", + "xltm", + "xltx", + "xm", + "xmind", + "xpi", + "xpm", + "xwd", + "xz", + "z", + "zip", + "zipx" +] diff --git a/node_modules/binary-extensions/binary-extensions.json.d.ts b/node_modules/binary-extensions/binary-extensions.json.d.ts new file mode 100644 index 0000000..94a248c --- /dev/null +++ b/node_modules/binary-extensions/binary-extensions.json.d.ts @@ -0,0 +1,3 @@ +declare const binaryExtensionsJson: readonly string[]; + +export = binaryExtensionsJson; diff --git a/node_modules/binary-extensions/index.d.ts b/node_modules/binary-extensions/index.d.ts new file mode 100644 index 0000000..f469ac5 --- /dev/null +++ b/node_modules/binary-extensions/index.d.ts @@ -0,0 +1,14 @@ +/** +List of binary file extensions. + +@example +``` +import binaryExtensions = require('binary-extensions'); + +console.log(binaryExtensions); +//=> ['3ds', '3g2', …] +``` +*/ +declare const binaryExtensions: readonly string[]; + +export = binaryExtensions; diff --git a/node_modules/binary-extensions/index.js b/node_modules/binary-extensions/index.js new file mode 100644 index 0000000..d46e468 --- /dev/null +++ b/node_modules/binary-extensions/index.js @@ -0,0 +1 @@ +module.exports = require('./binary-extensions.json'); diff --git a/node_modules/binary-extensions/license b/node_modules/binary-extensions/license new file mode 100644 index 0000000..5493a1a --- /dev/null +++ b/node_modules/binary-extensions/license @@ -0,0 +1,10 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) +Copyright (c) Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/binary-extensions/package.json b/node_modules/binary-extensions/package.json new file mode 100644 index 0000000..4710c33 --- /dev/null +++ b/node_modules/binary-extensions/package.json @@ -0,0 +1,40 @@ +{ + "name": "binary-extensions", + "version": "2.3.0", + "description": "List of binary file extensions", + "license": "MIT", + "repository": "sindresorhus/binary-extensions", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "sideEffects": false, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts", + "binary-extensions.json", + "binary-extensions.json.d.ts" + ], + "keywords": [ + "binary", + "extensions", + "extension", + "file", + "json", + "list", + "array" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/binary-extensions/readme.md b/node_modules/binary-extensions/readme.md new file mode 100644 index 0000000..88519b3 --- /dev/null +++ b/node_modules/binary-extensions/readme.md @@ -0,0 +1,25 @@ +# binary-extensions + +> List of binary file extensions + +The list is just a [JSON file](binary-extensions.json) and can be used anywhere. + +## Install + +```sh +npm install binary-extensions +``` + +## Usage + +```js +const binaryExtensions = require('binary-extensions'); + +console.log(binaryExtensions); +//=> ['3ds', '3g2', …] +``` + +## Related + +- [is-binary-path](https://github.com/sindresorhus/is-binary-path) - Check if a filepath is a binary file +- [text-extensions](https://github.com/sindresorhus/text-extensions) - List of text file extensions diff --git a/node_modules/body-parser/HISTORY.md b/node_modules/body-parser/HISTORY.md new file mode 100644 index 0000000..81d23e0 --- /dev/null +++ b/node_modules/body-parser/HISTORY.md @@ -0,0 +1,672 @@ +1.20.3 / 2024-09-10 +=================== + + * deps: qs@6.13.0 + * add `depth` option to customize the depth level in the parser + * IMPORTANT: The default `depth` level for parsing URL-encoded data is now `32` (previously was `Infinity`) + +1.20.2 / 2023-02-21 +=================== + + * Fix strict json error message on Node.js 19+ + * deps: content-type@~1.0.5 + - perf: skip value escaping when unnecessary + * deps: raw-body@2.5.2 + +1.20.1 / 2022-10-06 +=================== + + * deps: qs@6.11.0 + * perf: remove unnecessary object clone + +1.20.0 / 2022-04-02 +=================== + + * Fix error message for json parse whitespace in `strict` + * Fix internal error when inflated body exceeds limit + * Prevent loss of async hooks context + * Prevent hanging when request already read + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + * deps: qs@6.10.3 + * deps: raw-body@2.5.1 + - deps: http-errors@2.0.0 + +1.19.2 / 2022-02-15 +=================== + + * deps: bytes@3.1.2 + * deps: qs@6.9.7 + * Fix handling of `__proto__` keys + * deps: raw-body@2.4.3 + - deps: bytes@3.1.2 + +1.19.1 / 2021-12-10 +=================== + + * deps: bytes@3.1.1 + * deps: http-errors@1.8.1 + - deps: inherits@2.0.4 + - deps: toidentifier@1.0.1 + - deps: setprototypeof@1.2.0 + * deps: qs@6.9.6 + * deps: raw-body@2.4.2 + - deps: bytes@3.1.1 + - deps: http-errors@1.8.1 + * deps: safe-buffer@5.2.1 + * deps: type-is@~1.6.18 + +1.19.0 / 2019-04-25 +=================== + + * deps: bytes@3.1.0 + - Add petabyte (`pb`) support + * deps: http-errors@1.7.2 + - Set constructor name when possible + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: iconv-lite@0.4.24 + - Added encoding MIK + * deps: qs@6.7.0 + - Fix parsing array brackets after index + * deps: raw-body@2.4.0 + - deps: bytes@3.1.0 + - deps: http-errors@1.7.2 + - deps: iconv-lite@0.4.24 + * deps: type-is@~1.6.17 + - deps: mime-types@~2.1.24 + - perf: prevent internal `throw` on invalid type + +1.18.3 / 2018-05-14 +=================== + + * Fix stack trace for strict json parse error + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: http-errors@~1.6.3 + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.0 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.23 + - Fix loading encoding with year appended + - Fix deprecation warnings on Node.js 10+ + * deps: qs@6.5.2 + * deps: raw-body@2.3.3 + - deps: http-errors@1.6.3 + - deps: iconv-lite@0.4.23 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +1.18.2 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: remove argument reassignment + +1.18.1 / 2017-09-12 +=================== + + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: raw-body@2.3.2 + - deps: iconv-lite@0.4.19 + +1.18.0 / 2017-09-08 +=================== + + * Fix JSON strict violation error to match native parse error + * Include the `body` property on verify errors + * Include the `type` property on all generated errors + * Use `http-errors` to set status code on errors + * deps: bytes@3.0.0 + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + * deps: qs@6.5.0 + * deps: raw-body@2.3.1 + - Use `http-errors` for standard emitted errors + - deps: bytes@3.0.0 + - deps: iconv-lite@0.4.18 + - perf: skip buffer decoding on overage chunk + * perf: prevent internal `throw` when missing charset + +1.17.2 / 2017-05-17 +=================== + + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + +1.17.1 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +1.17.0 / 2017-03-01 +=================== + + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + * deps: qs@6.3.1 + - Fix compacting nested arrays + +1.16.1 / 2017-02-10 +=================== + + * deps: debug@2.6.1 + - Fix deprecation messages in WebStorm and other editors + - Undeprecate `DEBUG_FD` set to `1` or `2` + +1.16.0 / 2017-01-17 +=================== + + * deps: debug@2.6.0 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + * deps: qs@6.2.1 + - Fix array parsing from skipping empty values + * deps: raw-body@~2.2.0 + - deps: iconv-lite@0.4.15 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +1.15.2 / 2016-06-19 +=================== + + * deps: bytes@2.4.0 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: http-errors@~1.5.0 + - Use `setprototypeof` module to replace `__proto__` setting + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: qs@6.2.0 + * deps: raw-body@~2.1.7 + - deps: bytes@2.4.0 + - perf: remove double-cleanup on happy path + * deps: type-is@~1.6.13 + - deps: mime-types@~2.1.11 + +1.15.1 / 2016-05-05 +=================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + * deps: raw-body@~2.1.6 + - deps: bytes@2.3.0 + * deps: type-is@~1.6.12 + - deps: mime-types@~2.1.10 + +1.15.0 / 2016-02-10 +=================== + + * deps: http-errors@~1.4.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.2.1 < 2' + * deps: qs@6.1.0 + * deps: type-is@~1.6.11 + - deps: mime-types@~2.1.9 + +1.14.2 / 2015-12-16 +=================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + * deps: qs@5.2.0 + * deps: raw-body@~2.1.5 + - deps: bytes@2.2.0 + - deps: iconv-lite@0.4.13 + * deps: type-is@~1.6.10 + - deps: mime-types@~2.1.8 + +1.14.1 / 2015-09-27 +=================== + + * Fix issue where invalid charset results in 400 when `verify` used + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + * deps: raw-body@~2.1.4 + - Fix masking critical errors from `iconv-lite` + - deps: iconv-lite@0.4.12 + * deps: type-is@~1.6.9 + - deps: mime-types@~2.1.7 + +1.14.0 / 2015-09-16 +=================== + + * Fix JSON strict parse error to match syntax errors + * Provide static `require` analysis in `urlencoded` parser + * deps: depd@~1.1.0 + - Support web browser loading + * deps: qs@5.1.0 + * deps: raw-body@~2.1.3 + - Fix sync callback when attaching data listener causes sync read + * deps: type-is@~1.6.8 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.6 + +1.13.3 / 2015-07-31 +=================== + + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +1.13.2 / 2015-07-05 +=================== + + * deps: iconv-lite@0.4.11 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix user-visible incompatibilities from 3.1.0 + - Fix various parsing edge cases + * deps: raw-body@~2.1.2 + - Fix error stack traces to skip `makeError` + - deps: iconv-lite@0.4.11 + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +1.13.1 / 2015-06-16 +=================== + + * deps: qs@2.4.2 + - Downgraded from 3.1.0 because of user-visible incompatibilities + +1.13.0 / 2015-06-14 +=================== + + * Add `statusCode` property on `Error`s, in addition to `status` + * Change `type` default to `application/json` for JSON parser + * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser + * Provide static `require` analysis + * Use the `http-errors` module to generate errors + * deps: bytes@2.1.0 + - Slight optimizations + * deps: iconv-lite@0.4.10 + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + - Leading BOM is now removed when decoding + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: qs@3.1.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + - Parsed object now has `null` prototype + * deps: raw-body@~2.1.1 + - Use `unpipe` module for unpiping requests + - deps: iconv-lite@0.4.10 + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: remove argument reassignment + * perf: remove delete call + +1.12.4 / 2015-05-10 +=================== + + * deps: debug@~2.2.0 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: on-finished@~2.2.1 + * deps: raw-body@~2.0.1 + - Fix a false-positive when unpiping in Node.js 0.8 + - deps: bytes@2.0.1 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +1.12.3 / 2015-04-15 +=================== + + * Slight efficiency improvement when not debugging + * deps: depd@~1.0.1 + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + * deps: raw-body@1.3.4 + - Fix hanging callback if request aborts during read + - deps: iconv-lite@0.4.8 + +1.12.2 / 2015-03-16 +=================== + + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + +1.12.1 / 2015-03-15 +=================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +1.12.0 / 2015-02-13 +=================== + + * add `debug` messages + * accept a function for the `type` option + * use `content-type` to parse `Content-Type` headers + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + * deps: raw-body@1.3.3 + - deps: iconv-lite@0.4.7 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +1.11.0 / 2015-01-30 +=================== + + * make internal `extended: true` depth limit infinity + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +1.10.2 / 2015-01-20 +=================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + * deps: raw-body@1.3.2 + - deps: iconv-lite@0.4.6 + +1.10.1 / 2015-01-01 +=================== + + * deps: on-finished@~2.2.0 + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +1.10.0 / 2014-12-02 +=================== + + * make internal `extended: true` array limit dynamic + +1.9.3 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + * deps: raw-body@1.3.1 + - deps: iconv-lite@0.4.5 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +1.9.2 / 2014-10-27 +================== + + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +1.9.1 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +1.9.0 / 2014-09-24 +================== + + * include the charset in "unsupported charset" error message + * include the encoding in "unsupported content encoding" error message + * deps: depd@~1.0.0 + +1.8.4 / 2014-09-23 +================== + + * fix content encoding to be case-insensitive + +1.8.3 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +1.8.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + +1.8.1 / 2014-09-07 +================== + + * deps: media-typer@0.3.0 + * deps: type-is@~1.5.1 + +1.8.0 / 2014-09-05 +================== + + * make empty-body-handling consistent between chunked requests + - empty `json` produces `{}` + - empty `raw` produces `new Buffer(0)` + - empty `text` produces `''` + - empty `urlencoded` produces `{}` + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: type-is@~1.5.0 + - fix `hasbody` to be true for `content-length: 0` + +1.7.0 / 2014-09-01 +================== + + * add `parameterLimit` option to `urlencoded` parser + * change `urlencoded` extended array limit to 100 + * respond with 413 when over `parameterLimit` in `urlencoded` + +1.6.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +1.6.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +1.6.5 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.6.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + +1.6.3 / 2014-08-10 +================== + + * deps: qs@1.2.1 + +1.6.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +1.6.1 / 2014-08-06 +================== + + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +1.6.0 / 2014-08-05 +================== + + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + +1.5.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.5.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.5.0 / 2014-07-20 +================== + + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + * deps: raw-body@1.3.0 + - deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + - Fix `Cannot switch to old mode now` error on Node.js 0.10+ + * deps: type-is@~1.3.2 + +1.4.3 / 2014-06-19 +================== + + * deps: type-is@1.3.1 + - fix global variable leak + +1.4.2 / 2014-06-19 +================== + + * deps: type-is@1.3.0 + - improve type parsing + +1.4.1 / 2014-06-19 +================== + + * fix urlencoded extended deprecation message + +1.4.0 / 2014-06-19 +================== + + * add `text` parser + * add `raw` parser + * check accepted charset in content-type (accepts utf-8) + * check accepted encoding in content-encoding (accepts identity) + * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed + * deprecate `urlencoded()` without provided `extended` option + * lazy-load urlencoded parsers + * parsers split into files for reduced mem usage + * support gzip and deflate bodies + - set `inflate: false` to turn off + * deps: raw-body@1.2.2 + - Support all encodings from `iconv-lite` + +1.3.1 / 2014-06-11 +================== + + * deps: type-is@1.2.1 + - Switch dependency from mime to mime-types@1.0.0 + +1.3.0 / 2014-05-31 +================== + + * add `extended` option to urlencoded parser + +1.2.2 / 2014-05-27 +================== + + * deps: raw-body@1.1.6 + - assert stream encoding on node.js 0.8 + - assert stream encoding on node.js < 0.10.6 + - deps: bytes@1 + +1.2.1 / 2014-05-26 +================== + + * invoke `next(err)` after request fully read + - prevents hung responses and socket hang ups + +1.2.0 / 2014-05-11 +================== + + * add `verify` option + * deps: type-is@1.2.0 + - support suffix matching + +1.1.2 / 2014-05-11 +================== + + * improve json parser speed + +1.1.1 / 2014-05-11 +================== + + * fix repeated limit parsing with every request + +1.1.0 / 2014-05-10 +================== + + * add `type` option + * deps: pin for safety and consistency + +1.0.2 / 2014-04-14 +================== + + * use `type-is` module + +1.0.1 / 2014-03-20 +================== + + * lower default limits to 100kb diff --git a/node_modules/body-parser/LICENSE b/node_modules/body-parser/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/body-parser/README.md b/node_modules/body-parser/README.md new file mode 100644 index 0000000..f6661b7 --- /dev/null +++ b/node_modules/body-parser/README.md @@ -0,0 +1,476 @@ +# body-parser + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] + +Node.js body parsing middleware. + +Parse incoming request bodies in a middleware before your handlers, available +under the `req.body` property. + +**Note** As `req.body`'s shape is based on user-controlled input, all +properties and values in this object are untrusted and should be validated +before trusting. For example, `req.body.foo.toString()` may fail in multiple +ways, for example the `foo` property may not be there or may not be a string, +and `toString` may not be a function and instead a string or other user input. + +[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.org/package/busboy#readme) and + [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.org/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.org/package/formidable#readme) + * [multer](https://www.npmjs.org/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.org/package/body#readme) +- [co-body](https://www.npmjs.org/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + +```js +var bodyParser = require('body-parser') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body when +the `Content-Type` request header matches the `type` option, or an empty +object (`{}`) if there was no body to parse, the `Content-Type` was not matched, +or an error occurred. + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json([options]) + +Returns middleware that only parses `json` and only looks at requests where +the `Content-Type` header matches the `type` option. This parser accepts any +Unicode encoding of the body and supports automatic inflation of `gzip` and +`deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not a +function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `json`), a mime type (like `application/json`), or +a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a truthy +value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw([options]) + +Returns middleware that parses all bodies as a `Buffer` and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. +If not a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this +can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text([options]) + +Returns middleware that parses all bodies as a string and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `txt`), a mime type (like `text/plain`), or a mime +type with a wildcard (like `*/*` or `text/*`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a +truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded([options]) + +Returns middleware that only parses `urlencoded` bodies and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser accepts only UTF-8 encoding of the body and supports automatic +inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an optional `options` object that may contain +any of the following keys: + +##### extended + +The `extended` option allows to choose between parsing the URL-encoded data +with the `querystring` library (when `false`) or the `qs` library (when +`true`). The "extended" syntax allows for rich objects and arrays to be +encoded into the URL-encoded format, allowing for a JSON-like experience +with URL-encoded. For more information, please +[see the qs library](https://www.npmjs.org/package/qs#readme). + +Defaults to `true`, but using the default has been deprecated. Please +research into the difference between `qs` and `querystring` and choose the +appropriate setting. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +#### depth + +The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible. + +## Errors + +The middlewares provided by this module create errors using the +[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors +will typically have a `status`/`statusCode` property that contains the suggested +HTTP response code, an `expose` property to determine if the `message` property +should be displayed to the client, a `type` property to determine the type of +error without matching against the `message`, and a `body` property containing +the read body, if available. + +The following are the common errors created, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`, the `type` property is set to +`'encoding.unsupported'`, and the `charset` property will be set to the +encoding that is unsupported. + +### entity parse failed + +This error will occur when the request contained an entity that could not be +parsed by the middleware. The `status` property is set to `400`, the `type` +property is set to `'entity.parse.failed'`, and the `body` property is set to +the entity value that failed parsing. + +### entity verify failed + +This error will occur when the request contained an entity that could not be +failed verification by the defined `verify` option. The `status` property is +set to `403`, the `type` property is set to `'entity.verify.failed'`, and the +`body` property is set to the entity value that failed verification. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400` +and `type` property is set to `'request.aborted'`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413` and the `type` property is set to `'entity.too.large'`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400` and the `type` property +is set to `'request.size.invalid'`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500` and the `type` property is set to `'stream.encoding.set'`. + +### stream is not readable + +This error will occur when the request is no longer readable when this middleware +attempts to read it. This typically means something other than a middleware from +this module read the request body already and the middleware was also configured to +read the same request. The `status` property is set to `500` and the `type` +property is set to `'stream.not.readable'`. + +### too many parameters + +This error will occur when the content of the request exceeds the configured +`parameterLimit` for the `urlencoded` parser. The `status` property is set to +`413` and the `type` property is set to `'parameters.too.many'`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`, the +`type` property is set to `'charset.unsupported'`, and the `charset` property +is set to the charset that is unsupported. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`, +the `type` property is set to `'encoding.unsupported'`, and the `encoding` +property is set to the encoding that is unsupported. + +### The input exceeded the depth + +This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. When the `depth` option is set to `32` (default value), the error will not be thrown. + +## Examples + +### Express/Connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded({ extended: false })) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(JSON.stringify(req.body, null, 2)) +}) +``` + +### Express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommended way to use body-parser with +Express. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// create application/json parser +var jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +var urlencodedParser = bodyParser.urlencoded({ extended: false }) + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + // create user in req.body +}) +``` + +### Change accepted type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci +[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[node-version-image]: https://badgen.net/npm/node/body-parser +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/body-parser +[npm-url]: https://npmjs.org/package/body-parser +[npm-version-image]: https://badgen.net/npm/v/body-parser +[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge +[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser \ No newline at end of file diff --git a/node_modules/body-parser/SECURITY.md b/node_modules/body-parser/SECURITY.md new file mode 100644 index 0000000..9694d42 --- /dev/null +++ b/node_modules/body-parser/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The Express team and community take all security bugs seriously. Thank you +for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `body-parser`. This +information can be found in the npm registry using the command +`npm owner ls body-parser`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/expressjs/body-parser/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/node_modules/body-parser/index.js b/node_modules/body-parser/index.js new file mode 100644 index 0000000..bb24d73 --- /dev/null +++ b/node_modules/body-parser/index.js @@ -0,0 +1,156 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('body-parser') + +/** + * Cache of loaded parsers. + * @private + */ + +var parsers = Object.create(null) + +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ + +/** + * Module exports. + * @type {Parsers} + */ + +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') + +/** + * JSON parser. + * @public + */ + +Object.defineProperty(exports, 'json', { + configurable: true, + enumerable: true, + get: createParserGetter('json') +}) + +/** + * Raw parser. + * @public + */ + +Object.defineProperty(exports, 'raw', { + configurable: true, + enumerable: true, + get: createParserGetter('raw') +}) + +/** + * Text parser. + * @public + */ + +Object.defineProperty(exports, 'text', { + configurable: true, + enumerable: true, + get: createParserGetter('text') +}) + +/** + * URL-encoded parser. + * @public + */ + +Object.defineProperty(exports, 'urlencoded', { + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ + +function bodyParser (options) { + // use default type for parsers + var opts = Object.create(options || null, { + type: { + configurable: true, + enumerable: true, + value: undefined, + writable: true + } + }) + + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) + } +} + +/** + * Create a getter for loading a parser. + * @private + */ + +function createParserGetter (name) { + return function get () { + return loadParser(name) + } +} + +/** + * Load a parser module. + * @private + */ + +function loadParser (parserName) { + var parser = parsers[parserName] + + if (parser !== undefined) { + return parser + } + + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = require('./lib/types/json') + break + case 'raw': + parser = require('./lib/types/raw') + break + case 'text': + parser = require('./lib/types/text') + break + case 'urlencoded': + parser = require('./lib/types/urlencoded') + break + } + + // store to prevent invoking require() + return (parsers[parserName] = parser) +} diff --git a/node_modules/body-parser/lib/read.js b/node_modules/body-parser/lib/read.js new file mode 100644 index 0000000..fce6283 --- /dev/null +++ b/node_modules/body-parser/lib/read.js @@ -0,0 +1,205 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var destroy = require('destroy') +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var unpipe = require('unpipe') +var zlib = require('zlib') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} options + * @private + */ + +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream + + // flag as parsed + req._body = true + + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // unpipe from stream and destroy + if (stream !== req) { + unpipe(req) + destroy(stream, true) + } + + // read off entire request + dump(req, function onfinished () { + next(createError(400, _error)) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ + +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + return stream +} + +/** + * Dump the contents of a request. + * + * @param {object} req + * @param {function} callback + * @api private + */ + +function dump (req, callback) { + if (onFinished.isFinished(req)) { + callback(null) + } else { + onFinished(req, callback) + req.resume() + } +} diff --git a/node_modules/body-parser/lib/types/json.js b/node_modules/body-parser/lib/types/json.js new file mode 100644 index 0000000..59f3f7e --- /dev/null +++ b/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,247 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:json') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ + +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex + +var JSON_SYNTAX_CHAR = '#' +var JSON_SYNTAX_REGEXP = /#+/g + +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function json (options) { + var opts = options || {} + + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + } + + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } + } + + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.slice(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @return {Error} + * @private + */ + +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = '' + + if (index !== -1) { + partial = str.substring(0, index) + JSON_SYNTAX_CHAR + + for (var i = index + 1; i < str.length; i++) { + partial += JSON_SYNTAX_CHAR + } + } + + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) { + return str.substring(index, index + placeholder.length) + }), + stack: e.stack + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @private + */ + +function firstchar (str) { + var match = FIRST_CHAR_REGEXP.exec(str) + + return match + ? match[1] + : undefined +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} + */ + +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } + } + + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message + + return error +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/lib/types/raw.js b/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 0000000..f5d1b67 --- /dev/null +++ b/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,101 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var debug = require('debug')('body-parser:raw') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw (options) { + var opts = options || {} + + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function rawParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/lib/types/text.js b/node_modules/body-parser/lib/types/text.js new file mode 100644 index 0000000..083a009 --- /dev/null +++ b/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,121 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var debug = require('debug')('body-parser:text') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function text (options) { + var opts = options || {} + + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/lib/types/urlencoded.js b/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 0000000..2bd4485 --- /dev/null +++ b/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,307 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:urlencoded') +var deprecate = require('depd')('body-parser') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Cache of parser modules. + */ + +var parsers = Object.create(null) + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function urlencoded (options) { + var opts = options || {} + + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } + + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false + var depth = typeof opts.depth !== 'number' + ? Number(opts.depth || 32) + : opts.depth + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + return body.length + ? queryparse(body) + : {} + } + + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify, + depth: depth + }) + } +} + +/** + * Get the extended query parser. + * + * @param {object} options + */ + +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + + var depth = typeof options.depth !== 'number' + ? Number(options.depth || 32) + : options.depth + var parse = parser('qs') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isNaN(depth) || depth < 0) { + throw new TypeError('option depth must be a zero or a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + var arrayLimit = Math.max(100, paramCount) + + debug('parse extended urlencoding') + try { + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: depth, + strictDepth: true, + parameterLimit: parameterLimit + }) + } catch (err) { + if (err instanceof RangeError) { + throw createError(400, 'The input exceeded the depth', { + type: 'querystring.parse.rangeError' + }) + } else { + throw err + } + } + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ + +function parameterCount (body, limit) { + var count = 0 + var index = 0 + + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ + + if (count === limit) { + return undefined + } + } + + return count +} + +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ + +function parser (name) { + var mod = parsers[name] + + if (mod !== undefined) { + return mod.parse + } + + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = require('qs') + break + case 'querystring': + mod = require('querystring') + break + } + + // store to prevent invoking require() + parsers[name] = mod + + return mod.parse +} + +/** + * Get the simple query parser. + * + * @param {object} options + */ + +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + debug('parse urlencoding') + return parse(body, undefined, undefined, { maxKeys: parameterLimit }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/node_modules/debug/.coveralls.yml b/node_modules/body-parser/node_modules/debug/.coveralls.yml new file mode 100644 index 0000000..20a7068 --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/body-parser/node_modules/debug/.eslintrc b/node_modules/body-parser/node_modules/debug/.eslintrc new file mode 100644 index 0000000..8a37ae2 --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/.eslintrc @@ -0,0 +1,11 @@ +{ + "env": { + "browser": true, + "node": true + }, + "rules": { + "no-console": 0, + "no-empty": [1, { "allowEmptyCatch": true }] + }, + "extends": "eslint:recommended" +} diff --git a/node_modules/body-parser/node_modules/debug/.npmignore b/node_modules/body-parser/node_modules/debug/.npmignore new file mode 100644 index 0000000..5f60eec --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/node_modules/body-parser/node_modules/debug/.travis.yml b/node_modules/body-parser/node_modules/debug/.travis.yml new file mode 100644 index 0000000..6c6090c --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/.travis.yml @@ -0,0 +1,14 @@ + +language: node_js +node_js: + - "6" + - "5" + - "4" + +install: + - make node_modules + +script: + - make lint + - make test + - make coveralls diff --git a/node_modules/body-parser/node_modules/debug/CHANGELOG.md b/node_modules/body-parser/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000..eadaa18 --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/CHANGELOG.md @@ -0,0 +1,362 @@ + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/body-parser/node_modules/debug/LICENSE b/node_modules/body-parser/node_modules/debug/LICENSE new file mode 100644 index 0000000..658c933 --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/body-parser/node_modules/debug/Makefile b/node_modules/body-parser/node_modules/debug/Makefile new file mode 100644 index 0000000..584da8b --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/Makefile @@ -0,0 +1,50 @@ +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# Path +PATH := node_modules/.bin:$(PATH) +SHELL := /bin/bash + +# applications +NODE ?= $(shell which node) +YARN ?= $(shell which yarn) +PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +.FORCE: + +install: node_modules + +node_modules: package.json + @NODE_ENV= $(PKG) install + @touch node_modules + +lint: .FORCE + eslint browser.js debug.js index.js node.js + +test-node: .FORCE + istanbul cover node_modules/mocha/bin/_mocha -- test/**.js + +test-browser: .FORCE + mkdir -p dist + + @$(BROWSERIFY) \ + --standalone debug \ + . > dist/debug.js + + karma start --single-run + rimraf dist + +test: .FORCE + concurrently \ + "make test-node" \ + "make test-browser" + +coveralls: + cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js + +.PHONY: all install clean distclean diff --git a/node_modules/body-parser/node_modules/debug/README.md b/node_modules/body-parser/node_modules/debug/README.md new file mode 100644 index 0000000..f67be6b --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/README.md @@ -0,0 +1,312 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny node.js debugging utility modelled after node core's debugging technique. + +**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +#### Windows note + + On Windows the environment variable is set using the `set` command. + + ```cmd + set DEBUG=*,-not_this + ``` + + Note that PowerShell uses different syntax to set environment variables. + + ```cmd + $env:DEBUG = "*,-not_this" + ``` + +Then, run the program to be debugged as usual. + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". + +## Environment Variables + + When running through Node.js, you can set a few environment variables that will + change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + + __Note:__ The environment variables beginning with `DEBUG_` end up being + converted into an Options object that gets used with `%o`/`%O` formatters. + See the Node.js documentation for + [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) + for the complete list. + +## Formatters + + + Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + +### Custom formatters + + You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + +## Browser support + You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), + or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), + if you don't want to build it yourself. + + Debug's enable state is currently persisted by `localStorage`. + Consider the situation shown below where you have `worker:a` and `worker:b`, + and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +#### Web Inspector Colors + + Colors are also enabled on "Web Inspectors" that understand the `%c` formatting + option. These are WebKit web inspectors, Firefox ([since version + 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) + and the Firebug plugin for Firefox (any version). + + Colored output looks something like: + + ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example _stdout.js_: + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/body-parser/node_modules/debug/component.json b/node_modules/body-parser/node_modules/debug/component.json new file mode 100644 index 0000000..9de2641 --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.6.9", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "src/browser.js", + "scripts": [ + "src/browser.js", + "src/debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/node_modules/body-parser/node_modules/debug/karma.conf.js b/node_modules/body-parser/node_modules/debug/karma.conf.js new file mode 100644 index 0000000..103a82d --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/karma.conf.js @@ -0,0 +1,70 @@ +// Karma configuration +// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) + +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'chai', 'sinon'], + + + // list of files / patterns to load in the browser + files: [ + 'dist/debug.js', + 'test/*spec.js' + ], + + + // list of files to exclude + exclude: [ + 'src/node.js' + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: Infinity + }) +} diff --git a/node_modules/body-parser/node_modules/debug/node.js b/node_modules/body-parser/node_modules/debug/node.js new file mode 100644 index 0000000..7fc36fe --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/node_modules/body-parser/node_modules/debug/package.json b/node_modules/body-parser/node_modules/debug/package.json new file mode 100644 index 0000000..dc787ba --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/package.json @@ -0,0 +1,49 @@ +{ + "name": "debug", + "version": "2.6.9", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + }, + "devDependencies": { + "browserify": "9.0.3", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^2.11.15", + "eslint": "^3.12.1", + "istanbul": "^0.4.5", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-sinon": "^1.0.5", + "mocha": "^3.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "sinon": "^1.17.6", + "sinon-chai": "^2.8.0" + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + } +} diff --git a/node_modules/body-parser/node_modules/debug/src/browser.js b/node_modules/body-parser/node_modules/debug/src/browser.js new file mode 100644 index 0000000..7106924 --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/src/browser.js @@ -0,0 +1,185 @@ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * 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 + */ + +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') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var 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 + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // 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; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * 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 { + return window.localStorage; + } catch (e) {} +} diff --git a/node_modules/body-parser/node_modules/debug/src/debug.js b/node_modules/body-parser/node_modules/debug/src/debug.js new file mode 100644 index 0000000..6a5e3fc --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/src/debug.js @@ -0,0 +1,202 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.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". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var 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.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + 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; +} diff --git a/node_modules/body-parser/node_modules/debug/src/index.js b/node_modules/body-parser/node_modules/debug/src/index.js new file mode 100644 index 0000000..e12cf4d --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/body-parser/node_modules/debug/src/inspector-log.js b/node_modules/body-parser/node_modules/debug/src/inspector-log.js new file mode 100644 index 0000000..60ea6c0 --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/src/inspector-log.js @@ -0,0 +1,15 @@ +module.exports = inspectorLog; + +// black hole +const nullStream = new (require('stream').Writable)(); +nullStream._write = () => {}; + +/** + * Outputs a `console.log()` to the Node.js Inspector console *only*. + */ +function inspectorLog() { + const stdout = console._stdout; + console._stdout = nullStream; + console.log.apply(console, arguments); + console._stdout = stdout; +} diff --git a/node_modules/body-parser/node_modules/debug/src/node.js b/node_modules/body-parser/node_modules/debug/src/node.js new file mode 100644 index 0000000..b15109c --- /dev/null +++ b/node_modules/body-parser/node_modules/debug/src/node.js @@ -0,0 +1,248 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * 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(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var 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; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // 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; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = require('fs'); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = require('net'); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * 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 = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/node_modules/body-parser/node_modules/ms/index.js b/node_modules/body-parser/node_modules/ms/index.js new file mode 100644 index 0000000..6a522b1 --- /dev/null +++ b/node_modules/body-parser/node_modules/ms/index.js @@ -0,0 +1,152 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +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' && isNaN(val) === false) { + 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|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 '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) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} diff --git a/node_modules/body-parser/node_modules/ms/license.md b/node_modules/body-parser/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/body-parser/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/body-parser/node_modules/ms/package.json b/node_modules/body-parser/node_modules/ms/package.json new file mode 100644 index 0000000..6a31c81 --- /dev/null +++ b/node_modules/body-parser/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.0.0", + "description": "Tiny milisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "3.19.0", + "expect.js": "0.3.1", + "husky": "0.13.3", + "lint-staged": "3.4.1", + "mocha": "3.4.1" + } +} diff --git a/node_modules/body-parser/node_modules/ms/readme.md b/node_modules/body-parser/node_modules/ms/readme.md new file mode 100644 index 0000000..84a9974 --- /dev/null +++ b/node_modules/body-parser/node_modules/ms/readme.md @@ -0,0 +1,51 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +``` + +### Convert from milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +### Time format written-out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [node](https://nodejs.org) and in the browser. +- If a number is supplied to `ms`, a string with a unit is returned. +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). +- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. + +## Caught a bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/body-parser/package.json b/node_modules/body-parser/package.json new file mode 100644 index 0000000..3c9926f --- /dev/null +++ b/node_modules/body-parser/package.json @@ -0,0 +1,56 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "1.20.3", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "expressjs/body-parser", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "devDependencies": { + "eslint": "8.34.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-markdown": "3.0.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "methods": "1.1.2", + "mocha": "10.2.0", + "nyc": "15.1.0", + "safe-buffer": "5.2.1", + "supertest": "6.3.3" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "SECURITY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/brace-expansion/LICENSE b/node_modules/brace-expansion/LICENSE new file mode 100644 index 0000000..de32266 --- /dev/null +++ b/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/brace-expansion/README.md b/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..6b4e0e1 --- /dev/null +++ b/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/brace-expansion/index.js b/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..0478be8 --- /dev/null +++ b/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/node_modules/brace-expansion/package.json b/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..a18faa8 --- /dev/null +++ b/node_modules/brace-expansion/package.json @@ -0,0 +1,47 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "1.1.11", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh", + "bench": "matcha test/perf/bench.js" + }, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/braces/LICENSE b/node_modules/braces/LICENSE new file mode 100644 index 0000000..9af4a67 --- /dev/null +++ b/node_modules/braces/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/braces/README.md b/node_modules/braces/README.md new file mode 100644 index 0000000..f59dd60 --- /dev/null +++ b/node_modules/braces/README.md @@ -0,0 +1,586 @@ +# braces [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM monthly downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![NPM total downloads](https://img.shields.io/npm/dt/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Linux Build Status](https://img.shields.io/travis/micromatch/braces.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/braces) + +> Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save braces +``` + +## v3.0.0 Released!! + +See the [changelog](CHANGELOG.md) for details. + +## Why use braces? + +Brace patterns make globs more powerful by adding the ability to match specific ranges and sequences of characters. + +- **Accurate** - complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests) +- **[fast and performant](#benchmarks)** - Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity. +- **Organized code base** - The parser and compiler are easy to maintain and update when edge cases crop up. +- **Well-tested** - Thousands of test assertions, and passes all of the Bash, minimatch, and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests (as of the date this was written). +- **Safer** - You shouldn't have to worry about users defining aggressive or malicious brace patterns that can break your application. Braces takes measures to prevent malicious regex that can be used for DDoS attacks (see [catastrophic backtracking](https://www.regular-expressions.info/catastrophic.html)). +- [Supports lists](#lists) - (aka "sets") `a/{b,c}/d` => `['a/b/d', 'a/c/d']` +- [Supports sequences](#sequences) - (aka "ranges") `{01..03}` => `['01', '02', '03']` +- [Supports steps](#steps) - (aka "increments") `{2..10..2}` => `['2', '4', '6', '8', '10']` +- [Supports escaping](#escaping) - To prevent evaluation of special characters. + +## Usage + +The main export is a function that takes one or more brace `patterns` and `options`. + +```js +const braces = require('braces'); +// braces(patterns[, options]); + +console.log(braces(['{01..05}', '{a..e}'])); +//=> ['(0[1-5])', '([a-e])'] + +console.log(braces(['{01..05}', '{a..e}'], { expand: true })); +//=> ['01', '02', '03', '04', '05', 'a', 'b', 'c', 'd', 'e'] +``` + +### Brace Expansion vs. Compilation + +By default, brace patterns are compiled into strings that are optimized for creating regular expressions and matching. + +**Compiled** + +```js +console.log(braces('a/{x,y,z}/b')); +//=> ['a/(x|y|z)/b'] +console.log(braces(['a/{01..20}/b', 'a/{1..5}/b'])); +//=> [ 'a/(0[1-9]|1[0-9]|20)/b', 'a/([1-5])/b' ] +``` + +**Expanded** + +Enable brace expansion by setting the `expand` option to true, or by using [braces.expand()](#expand) (returns an array similar to what you'd expect from Bash, or `echo {1..5}`, or [minimatch](https://github.com/isaacs/minimatch)): + +```js +console.log(braces('a/{x,y,z}/b', { expand: true })); +//=> ['a/x/b', 'a/y/b', 'a/z/b'] + +console.log(braces.expand('{01..10}')); +//=> ['01','02','03','04','05','06','07','08','09','10'] +``` + +### Lists + +Expand lists (like Bash "sets"): + +```js +console.log(braces('a/{foo,bar,baz}/*.js')); +//=> ['a/(foo|bar|baz)/*.js'] + +console.log(braces.expand('a/{foo,bar,baz}/*.js')); +//=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js'] +``` + +### Sequences + +Expand ranges of characters (like Bash "sequences"): + +```js +console.log(braces.expand('{1..3}')); // ['1', '2', '3'] +console.log(braces.expand('a/{1..3}/b')); // ['a/1/b', 'a/2/b', 'a/3/b'] +console.log(braces('{a..c}', { expand: true })); // ['a', 'b', 'c'] +console.log(braces('foo/{a..c}', { expand: true })); // ['foo/a', 'foo/b', 'foo/c'] + +// supports zero-padded ranges +console.log(braces('a/{01..03}/b')); //=> ['a/(0[1-3])/b'] +console.log(braces('a/{001..300}/b')); //=> ['a/(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)/b'] +``` + +See [fill-range](https://github.com/jonschlinkert/fill-range) for all available range-expansion options. + +### Steppped ranges + +Steps, or increments, may be used with ranges: + +```js +console.log(braces.expand('{2..10..2}')); +//=> ['2', '4', '6', '8', '10'] + +console.log(braces('{2..10..2}')); +//=> ['(2|4|6|8|10)'] +``` + +When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion. + +### Nesting + +Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved. + +**"Expanded" braces** + +```js +console.log(braces.expand('a{b,c,/{x,y}}/e')); +//=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e'] + +console.log(braces.expand('a/{x,{1..5},y}/c')); +//=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c'] +``` + +**"Optimized" braces** + +```js +console.log(braces('a{b,c,/{x,y}}/e')); +//=> ['a(b|c|/(x|y))/e'] + +console.log(braces('a/{x,{1..5},y}/c')); +//=> ['a/(x|([1-5])|y)/c'] +``` + +### Escaping + +**Escaping braces** + +A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_: + +```js +console.log(braces.expand('a\\{d,c,b}e')); +//=> ['a{d,c,b}e'] + +console.log(braces.expand('a{d,c,b\\}e')); +//=> ['a{d,c,b}e'] +``` + +**Escaping commas** + +Commas inside braces may also be escaped: + +```js +console.log(braces.expand('a{b\\,c}d')); +//=> ['a{b,c}d'] + +console.log(braces.expand('a{d\\,c,b}e')); +//=> ['ad,ce', 'abe'] +``` + +**Single items** + +Following bash conventions, a brace pattern is also not expanded when it contains a single character: + +```js +console.log(braces.expand('a{b}c')); +//=> ['a{b}c'] +``` + +## Options + +### options.maxLength + +**Type**: `Number` + +**Default**: `10,000` + +**Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera. + +```js +console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error +``` + +### options.expand + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Generate an "expanded" brace pattern (alternatively you can use the `braces.expand()` method, which does the same thing). + +```js +console.log(braces('a/{b,c}/d', { expand: true })); +//=> [ 'a/b/d', 'a/c/d' ] +``` + +### options.nodupes + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Remove duplicates from the returned array. + +### options.rangeLimit + +**Type**: `Number` + +**Default**: `1000` + +**Description**: To prevent malicious patterns from being passed by users, an error is thrown when `braces.expand()` is used or `options.expand` is true and the generated range will exceed the `rangeLimit`. + +You can customize `options.rangeLimit` or set it to `Inifinity` to disable this altogether. + +**Examples** + +```js +// pattern exceeds the "rangeLimit", so it's optimized automatically +console.log(braces.expand('{1..1000}')); +//=> ['([1-9]|[1-9][0-9]{1,2}|1000)'] + +// pattern does not exceed "rangeLimit", so it's NOT optimized +console.log(braces.expand('{1..100}')); +//=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100'] +``` + +### options.transform + +**Type**: `Function` + +**Default**: `undefined` + +**Description**: Customize range expansion. + +**Example: Transforming non-numeric values** + +```js +const alpha = braces.expand('x/{a..e}/y', { + transform(value, index) { + // When non-numeric values are passed, "value" is a character code. + return 'foo/' + String.fromCharCode(value) + '-' + index; + }, +}); +console.log(alpha); +//=> [ 'x/foo/a-0/y', 'x/foo/b-1/y', 'x/foo/c-2/y', 'x/foo/d-3/y', 'x/foo/e-4/y' ] +``` + +**Example: Transforming numeric values** + +```js +const numeric = braces.expand('{1..5}', { + transform(value) { + // when numeric values are passed, "value" is a number + return 'foo/' + value * 2; + }, +}); +console.log(numeric); +//=> [ 'foo/2', 'foo/4', 'foo/6', 'foo/8', 'foo/10' ] +``` + +### options.quantifiers + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: In regular expressions, quanitifiers can be used to specify how many times a token can be repeated. For example, `a{1,3}` will match the letter `a` one to three times. + +Unfortunately, regex quantifiers happen to share the same syntax as [Bash lists](#lists) + +The `quantifiers` option tells braces to detect when [regex quantifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#quantifiers) are defined in the given pattern, and not to try to expand them as lists. + +**Examples** + +```js +const braces = require('braces'); +console.log(braces('a/b{1,3}/{x,y,z}')); +//=> [ 'a/b(1|3)/(x|y|z)' ] +console.log(braces('a/b{1,3}/{x,y,z}', { quantifiers: true })); +//=> [ 'a/b{1,3}/(x|y|z)' ] +console.log(braces('a/b{1,3}/{x,y,z}', { quantifiers: true, expand: true })); +//=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ] +``` + +### options.keepEscaping + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Do not strip backslashes that were used for escaping from the result. + +## What is "brace expansion"? + +Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs). + +In addition to "expansion", braces are also used for matching. In other words: + +- [brace expansion](#brace-expansion) is for generating new lists +- [brace matching](#brace-matching) is for filtering existing lists + +
+More about brace expansion (click to expand) + +There are two main types of brace expansion: + +1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}` +2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges". + +Here are some example brace patterns to illustrate how they work: + +**Sets** + +``` +{a,b,c} => a b c +{a,b,c}{1,2} => a1 a2 b1 b2 c1 c2 +``` + +**Sequences** + +``` +{1..9} => 1 2 3 4 5 6 7 8 9 +{4..-4} => 4 3 2 1 0 -1 -2 -3 -4 +{1..20..3} => 1 4 7 10 13 16 19 +{a..j} => a b c d e f g h i j +{j..a} => j i h g f e d c b a +{a..z..3} => a d g j m p s v y +``` + +**Combination** + +Sets and sequences can be mixed together or used along with any other strings. + +``` +{a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3 +foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar +``` + +The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases. + +## Brace matching + +In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching. + +For example, the pattern `foo/{1..3}/bar` would match any of following strings: + +``` +foo/1/bar +foo/2/bar +foo/3/bar +``` + +But not: + +``` +baz/1/qux +baz/2/qux +baz/3/qux +``` + +Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings: + +``` +foo/1/bar +foo/2/bar +foo/3/bar +baz/1/qux +baz/2/qux +baz/3/qux +``` + +## Brace matching pitfalls + +Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of. + +### tldr + +**"brace bombs"** + +- brace expansion can eat up a huge amount of processing resources +- as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially +- users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!) + +For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section. + +### The solution + +Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries. + +### Geometric complexity + +At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`. + +For example, the following sets demonstrate quadratic (`O(n^2)`) complexity: + +``` +{1,2}{3,4} => (2X2) => 13 14 23 24 +{1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246 +``` + +But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity: + +``` +{1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248 + 249 257 258 259 267 268 269 347 348 349 357 + 358 359 367 368 369 +``` + +Now, imagine how this complexity grows given that each element is a n-tuple: + +``` +{1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB) +{1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB) +``` + +Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control. + +**More information** + +Interested in learning more about brace expansion? + +- [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion) +- [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion) +- [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) + +
+ +## Performance + +Braces is not only screaming fast, it's also more accurate the other brace expansion libraries. + +### Better algorithms + +Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_. + +Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently. + +**The proof is in the numbers** + +Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively. + +| **Pattern** | **braces** | **[minimatch][]** | +| --------------------------- | ------------------- | ---------------------------- | +| `{1..9007199254740991}`[^1] | `298 B` (5ms 459μs) | N/A (freezes) | +| `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) | +| `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) | +| `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) | +| `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) | +| `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) | +| `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) | +| `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) | +| `{1..100000000}` | `33 B` (733μs) | N/A (freezes) | +| `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) | +| `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) | +| `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) | +| `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) | +| `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) | +| `{1..100}` | `22 B` (345μs) | `291 B` (196μs) | +| `{1..10}` | `10 B` (533μs) | `20 B` (37μs) | +| `{1..3}` | `7 B` (190μs) | `5 B` (27μs) | + +### Faster algorithms + +When you need expansion, braces is still much faster. + +_(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_ + +| **Pattern** | **braces** | **[minimatch][]** | +| --------------- | --------------------------- | ---------------------------- | +| `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) | +| `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) | +| `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) | +| `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) | +| `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) | +| `{1..100}` | `291 B` (424μs) | `291 B` (211μs) | +| `{1..10}` | `20 B` (487μs) | `20 B` (72μs) | +| `{1..3}` | `5 B` (166μs) | `5 B` (27μs) | + +If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js). + +## Benchmarks + +### Running benchmarks + +Install dev dependencies: + +```bash +npm i -d && npm benchmark +``` + +### Latest results + +Braces is more accurate, without sacrificing performance. + +```bash +● expand - range (expanded) + braces x 53,167 ops/sec ±0.12% (102 runs sampled) + minimatch x 11,378 ops/sec ±0.10% (102 runs sampled) +● expand - range (optimized for regex) + braces x 373,442 ops/sec ±0.04% (100 runs sampled) + minimatch x 3,262 ops/sec ±0.18% (100 runs sampled) +● expand - nested ranges (expanded) + braces x 33,921 ops/sec ±0.09% (99 runs sampled) + minimatch x 10,855 ops/sec ±0.28% (100 runs sampled) +● expand - nested ranges (optimized for regex) + braces x 287,479 ops/sec ±0.52% (98 runs sampled) + minimatch x 3,219 ops/sec ±0.28% (101 runs sampled) +● expand - set (expanded) + braces x 238,243 ops/sec ±0.19% (97 runs sampled) + minimatch x 538,268 ops/sec ±0.31% (96 runs sampled) +● expand - set (optimized for regex) + braces x 321,844 ops/sec ±0.10% (97 runs sampled) + minimatch x 140,600 ops/sec ±0.15% (100 runs sampled) +● expand - nested sets (expanded) + braces x 165,371 ops/sec ±0.42% (96 runs sampled) + minimatch x 337,720 ops/sec ±0.28% (100 runs sampled) +● expand - nested sets (optimized for regex) + braces x 242,948 ops/sec ±0.12% (99 runs sampled) + minimatch x 87,403 ops/sec ±0.79% (96 runs sampled) +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Contributors + +| **Commits** | **Contributor** | +| ----------- | ------------------------------------------------------------- | +| 197 | [jonschlinkert](https://github.com/jonschlinkert) | +| 4 | [doowb](https://github.com/doowb) | +| 1 | [es128](https://github.com/es128) | +| 1 | [eush77](https://github.com/eush77) | +| 1 | [hemanth](https://github.com/hemanth) | +| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | + +### Author + +**Jon Schlinkert** + +- [GitHub Profile](https://github.com/jonschlinkert) +- [Twitter Profile](https://twitter.com/jonschlinkert) +- [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +--- + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ diff --git a/node_modules/braces/index.js b/node_modules/braces/index.js new file mode 100644 index 0000000..d222c13 --- /dev/null +++ b/node_modules/braces/index.js @@ -0,0 +1,170 @@ +'use strict'; + +const stringify = require('./lib/stringify'); +const compile = require('./lib/compile'); +const expand = require('./lib/expand'); +const parse = require('./lib/parse'); + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +const braces = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (const pattern of input) { + const result = braces.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces.create(input, options)); + } + + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + +braces.parse = (input, options = {}) => parse(input, options); + +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify(braces.parse(input, options), options); + } + return stringify(input, options); +}; + +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + return compile(input, options); +}; + +/** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + + let result = expand(input, options); + + // filter out empty strings if specified + if (options.noempty === true) { + result = result.filter(Boolean); + } + + // filter out duplicates if specified + if (options.nodupes === true) { + result = [...new Set(result)]; + } + + return result; +}; + +/** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true + ? braces.compile(input, options) + : braces.expand(input, options); +}; + +/** + * Expose "braces" + */ + +module.exports = braces; diff --git a/node_modules/braces/lib/compile.js b/node_modules/braces/lib/compile.js new file mode 100644 index 0000000..dce69be --- /dev/null +++ b/node_modules/braces/lib/compile.js @@ -0,0 +1,60 @@ +'use strict'; + +const fill = require('fill-range'); +const utils = require('./utils'); + +const compile = (ast, options = {}) => { + const walk = (node, parent = {}) => { + const invalidBlock = utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + const invalid = invalidBlock === true || invalidNode === true; + const prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + + if (node.isClose === true) { + console.log('node.isClose', prefix, node.value); + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? prefix + node.value : '('; + } + + if (node.type === 'close') { + return invalid ? prefix + node.value : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); + const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (const child of node.nodes) { + output += walk(child, node); + } + } + + return output; + }; + + return walk(ast); +}; + +module.exports = compile; diff --git a/node_modules/braces/lib/constants.js b/node_modules/braces/lib/constants.js new file mode 100644 index 0000000..2bb3b88 --- /dev/null +++ b/node_modules/braces/lib/constants.js @@ -0,0 +1,57 @@ +'use strict'; + +module.exports = { + MAX_LENGTH: 10000, + + // Digits + CHAR_0: '0', /* 0 */ + CHAR_9: '9', /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', /* A */ + CHAR_LOWERCASE_A: 'a', /* a */ + CHAR_UPPERCASE_Z: 'Z', /* Z */ + CHAR_LOWERCASE_Z: 'z', /* z */ + + CHAR_LEFT_PARENTHESES: '(', /* ( */ + CHAR_RIGHT_PARENTHESES: ')', /* ) */ + + CHAR_ASTERISK: '*', /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', /* & */ + CHAR_AT: '@', /* @ */ + CHAR_BACKSLASH: '\\', /* \ */ + CHAR_BACKTICK: '`', /* ` */ + CHAR_CARRIAGE_RETURN: '\r', /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ + CHAR_COLON: ':', /* : */ + CHAR_COMMA: ',', /* , */ + CHAR_DOLLAR: '$', /* . */ + CHAR_DOT: '.', /* . */ + CHAR_DOUBLE_QUOTE: '"', /* " */ + CHAR_EQUAL: '=', /* = */ + CHAR_EXCLAMATION_MARK: '!', /* ! */ + CHAR_FORM_FEED: '\f', /* \f */ + CHAR_FORWARD_SLASH: '/', /* / */ + CHAR_HASH: '#', /* # */ + CHAR_HYPHEN_MINUS: '-', /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ + CHAR_LEFT_CURLY_BRACE: '{', /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ + CHAR_LINE_FEED: '\n', /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ + CHAR_PERCENT: '%', /* % */ + CHAR_PLUS: '+', /* + */ + CHAR_QUESTION_MARK: '?', /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ + CHAR_SEMICOLON: ';', /* ; */ + CHAR_SINGLE_QUOTE: '\'', /* ' */ + CHAR_SPACE: ' ', /* */ + CHAR_TAB: '\t', /* \t */ + CHAR_UNDERSCORE: '_', /* _ */ + CHAR_VERTICAL_LINE: '|', /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ +}; diff --git a/node_modules/braces/lib/expand.js b/node_modules/braces/lib/expand.js new file mode 100644 index 0000000..35b2c41 --- /dev/null +++ b/node_modules/braces/lib/expand.js @@ -0,0 +1,113 @@ +'use strict'; + +const fill = require('fill-range'); +const stringify = require('./stringify'); +const utils = require('./utils'); + +const append = (queue = '', stash = '', enclose = false) => { + const result = []; + + queue = [].concat(queue); + stash = [].concat(stash); + + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (const item of queue) { + if (Array.isArray(item)) { + for (const value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); + } + } + } + return utils.flatten(result); +}; + +const expand = (ast, options = {}) => { + const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; + + const walk = (node, parent = {}) => { + node.queue = []; + + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); + + if (utils.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fill(...args, options); + if (range.length === 0) { + range = stringify(node, options); + } + + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + + const enclose = utils.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + const child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils.flatten(walk(ast)); +}; + +module.exports = expand; diff --git a/node_modules/braces/lib/parse.js b/node_modules/braces/lib/parse.js new file mode 100644 index 0000000..3a6988e --- /dev/null +++ b/node_modules/braces/lib/parse.js @@ -0,0 +1,331 @@ +'use strict'; + +const stringify = require('./stringify'); + +/** + * Constants + */ + +const { + MAX_LENGTH, + CHAR_BACKSLASH, /* \ */ + CHAR_BACKTICK, /* ` */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_RIGHT_SQUARE_BRACKET, /* ] */ + CHAR_DOUBLE_QUOTE, /* " */ + CHAR_SINGLE_QUOTE, /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = require('./constants'); + +/** + * parse + */ + +const parse = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + const opts = options || {}; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + const ast = { type: 'root', input, nodes: [] }; + const stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + const length = input.length; + let index = 0; + let depth = 0; + let value; + + /** + * Helpers + */ + + const advance = () => input[index++]; + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ type: 'bos' }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + + /** + * Escaped chars + */ + + if (value === CHAR_BACKSLASH) { + push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); + continue; + } + + /** + * Right square bracket (literal): ']' + */ + + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push({ type: 'text', value: '\\' + value }); + continue; + } + + /** + * Left square bracket: '[' + */ + + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ type: 'text', value }); + continue; + } + + /** + * Parentheses + */ + + if (value === CHAR_LEFT_PARENTHESES) { + block = push({ type: 'paren', nodes: [] }); + stack.push(block); + push({ type: 'text', value }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== 'paren') { + push({ type: 'text', value }); + continue; + } + block = stack.pop(); + push({ type: 'text', value }); + block = stack[stack.length - 1]; + continue; + } + + /** + * Quotes: '|"|` + */ + + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + const open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Left curly brace: '{' + */ + + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + + const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + const brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + + block = push(brace); + stack.push(block); + push({ type: 'open', value }); + continue; + } + + /** + * Right curly brace: '}' + */ + + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== 'brace') { + push({ type: 'text', value }); + continue; + } + + const type = 'close'; + block = stack.pop(); + block.close = true; + + push({ type, value }); + depth--; + + block = stack[stack.length - 1]; + continue; + } + + /** + * Comma: ',' + */ + + if (value === CHAR_COMMA && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + const open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify(block) }]; + } + + push({ type: 'comma', value }); + block.commas++; + continue; + } + + /** + * Dot: '.' + */ + + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + const siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ type: 'text', value }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + + const before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ type: 'dot', value }); + continue; + } + + /** + * Text + */ + + push({ type: 'text', value }); + } + + // Mark imbalanced braces and brackets as invalid + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); + + // get the location of the block on parent.nodes (block's siblings) + const parent = stack[stack.length - 1]; + const index = parent.nodes.indexOf(block); + // replace the (invalid) block with it's nodes + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ type: 'eos' }); + return ast; +}; + +module.exports = parse; diff --git a/node_modules/braces/lib/stringify.js b/node_modules/braces/lib/stringify.js new file mode 100644 index 0000000..8bcf872 --- /dev/null +++ b/node_modules/braces/lib/stringify.js @@ -0,0 +1,32 @@ +'use strict'; + +const utils = require('./utils'); + +module.exports = (ast, options = {}) => { + const stringify = (node, parent = {}) => { + const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { + return '\\' + node.value; + } + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (const child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + + return stringify(ast); +}; + diff --git a/node_modules/braces/lib/utils.js b/node_modules/braces/lib/utils.js new file mode 100644 index 0000000..d19311f --- /dev/null +++ b/node_modules/braces/lib/utils.js @@ -0,0 +1,122 @@ +'use strict'; + +exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; +}; + +/** + * Find a node of the given type + */ + +exports.find = (node, type) => node.nodes.find(node => node.type === type); + +/** + * Find a node of the given type + */ + +exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return ((Number(max) - Number(min)) / Number(step)) >= limit; +}; + +/** + * Escape the given node with '\\' before node.value + */ + +exports.escapeNode = (block, n = 0, type) => { + const node = block.nodes[n]; + if (!node) return; + + if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } +}; + +/** + * Returns true if the given brace node should be enclosed in literal braces + */ + +exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + if ((node.commas >> 0 + node.ranges >> 0) === 0) { + node.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a brace node is invalid. + */ + +exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + if ((block.commas >> 0 + block.ranges >> 0) === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a node is an open or close node + */ + +exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + return node.open === true || node.close === true; +}; + +/** + * Reduce an array of text nodes. + */ + +exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; +}, []); + +/** + * Flatten an array + */ + +exports.flatten = (...args) => { + const result = []; + + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + const ele = arr[i]; + + if (Array.isArray(ele)) { + flat(ele); + continue; + } + + if (ele !== undefined) { + result.push(ele); + } + } + return result; + }; + + flat(args); + return result; +}; diff --git a/node_modules/braces/package.json b/node_modules/braces/package.json new file mode 100644 index 0000000..c3c056e --- /dev/null +++ b/node_modules/braces/package.json @@ -0,0 +1,77 @@ +{ + "name": "braces", + "description": "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.", + "version": "3.0.3", + "homepage": "https://github.com/micromatch/braces", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Brian Woodward (https://twitter.com/doowb)", + "Elan Shanker (https://github.com/es128)", + "Eugene Sharygin (https://github.com/eush77)", + "hemanth.hm (http://h3manth.com)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)" + ], + "repository": "micromatch/braces", + "bugs": { + "url": "https://github.com/micromatch/braces/issues" + }, + "license": "MIT", + "files": [ + "index.js", + "lib" + ], + "main": "index.js", + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "mocha", + "benchmark": "node benchmark" + }, + "dependencies": { + "fill-range": "^7.1.1" + }, + "devDependencies": { + "ansi-colors": "^3.2.4", + "bash-path": "^2.0.1", + "gulp-format-md": "^2.0.0", + "mocha": "^6.1.1" + }, + "keywords": [ + "alpha", + "alphabetical", + "bash", + "brace", + "braces", + "expand", + "expansion", + "filepath", + "fill", + "fs", + "glob", + "globbing", + "letter", + "match", + "matches", + "matching", + "number", + "numerical", + "path", + "range", + "ranges", + "sh" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "lint": { + "reflinks": true + }, + "plugins": [ + "gulp-format-md" + ] + } +} diff --git a/node_modules/buffer-equal-constant-time/.npmignore b/node_modules/buffer-equal-constant-time/.npmignore new file mode 100644 index 0000000..34e4f5c --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.npmignore @@ -0,0 +1,2 @@ +.*.sw[mnop] +node_modules/ diff --git a/node_modules/buffer-equal-constant-time/.travis.yml b/node_modules/buffer-equal-constant-time/.travis.yml new file mode 100644 index 0000000..78e1c01 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: +- "0.11" +- "0.10" diff --git a/node_modules/buffer-equal-constant-time/LICENSE.txt b/node_modules/buffer-equal-constant-time/LICENSE.txt new file mode 100644 index 0000000..9a064f3 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (c) 2013, GoInstant Inc., a salesforce.com company +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of salesforce.com, nor GoInstant, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/buffer-equal-constant-time/README.md b/node_modules/buffer-equal-constant-time/README.md new file mode 100644 index 0000000..4f227f5 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/README.md @@ -0,0 +1,50 @@ +# buffer-equal-constant-time + +Constant-time `Buffer` comparison for node.js. Should work with browserify too. + +[![Build Status](https://travis-ci.org/goinstant/buffer-equal-constant-time.png?branch=master)](https://travis-ci.org/goinstant/buffer-equal-constant-time) + +```sh + npm install buffer-equal-constant-time +``` + +# Usage + +```js + var bufferEq = require('buffer-equal-constant-time'); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (bufferEq(a,b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +If you'd like to install an `.equal()` method onto the node.js `Buffer` and +`SlowBuffer` prototypes: + +```js + require('buffer-equal-constant-time').install(); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (a.equal(b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +To get rid of the installed `.equal()` method, call `.restore()`: + +```js + require('buffer-equal-constant-time').restore(); +``` + +# Legal + +© 2013 GoInstant Inc., a salesforce.com company + +Licensed under the BSD 3-clause license. diff --git a/node_modules/buffer-equal-constant-time/index.js b/node_modules/buffer-equal-constant-time/index.js new file mode 100644 index 0000000..5462c1f --- /dev/null +++ b/node_modules/buffer-equal-constant-time/index.js @@ -0,0 +1,41 @@ +/*jshint node:true */ +'use strict'; +var Buffer = require('buffer').Buffer; // browserify +var SlowBuffer = require('buffer').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; +}; diff --git a/node_modules/buffer-equal-constant-time/package.json b/node_modules/buffer-equal-constant-time/package.json new file mode 100644 index 0000000..17c7de2 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/package.json @@ -0,0 +1,21 @@ +{ + "name": "buffer-equal-constant-time", + "version": "1.0.1", + "description": "Constant-time comparison of Buffers", + "main": "index.js", + "scripts": { + "test": "mocha test.js" + }, + "repository": "git@github.com:goinstant/buffer-equal-constant-time.git", + "keywords": [ + "buffer", + "equal", + "constant-time", + "crypto" + ], + "author": "GoInstant Inc., a salesforce.com company", + "license": "BSD-3-Clause", + "devDependencies": { + "mocha": "~1.15.1" + } +} diff --git a/node_modules/buffer-equal-constant-time/test.js b/node_modules/buffer-equal-constant-time/test.js new file mode 100644 index 0000000..0bc972d --- /dev/null +++ b/node_modules/buffer-equal-constant-time/test.js @@ -0,0 +1,42 @@ +/*jshint node:true */ +'use strict'; + +var bufferEq = require('./index'); +var assert = require('assert'); + +describe('buffer-equal-constant-time', function() { + var a = new Buffer('asdfasdf123456'); + var b = new Buffer('asdfasdf123456'); + var c = new Buffer('asdfasdf'); + + describe('bufferEq', function() { + it('says a == b', function() { + assert.strictEqual(bufferEq(a, b), true); + }); + + it('says a != c', function() { + assert.strictEqual(bufferEq(a, c), false); + }); + }); + + describe('install/restore', function() { + before(function() { + bufferEq.install(); + }); + after(function() { + bufferEq.restore(); + }); + + it('installed an .equal method', function() { + var SlowBuffer = require('buffer').SlowBuffer; + assert.ok(Buffer.prototype.equal); + assert.ok(SlowBuffer.prototype.equal); + }); + + it('infected existing Buffers', function() { + assert.strictEqual(a.equal(b), true); + assert.strictEqual(a.equal(c), false); + }); + }); + +}); diff --git a/node_modules/bytes/History.md b/node_modules/bytes/History.md new file mode 100644 index 0000000..d60ce0e --- /dev/null +++ b/node_modules/bytes/History.md @@ -0,0 +1,97 @@ +3.1.2 / 2022-01-27 +================== + + * Fix return value for un-parsable strings + +3.1.1 / 2021-11-15 +================== + + * Fix "thousandsSeparator" incorrecting formatting fractional part + +3.1.0 / 2019-01-22 +================== + + * Add petabyte (`pb`) support + +3.0.0 / 2017-08-31 +================== + + * Change "kB" to "KB" in format output + * Remove support for Node.js 0.6 + * Remove support for ComponentJS + +2.5.0 / 2017-03-24 +================== + + * Add option "unit" + +2.4.0 / 2016-06-01 +================== + + * Add option "unitSeparator" + +2.3.0 / 2016-02-15 +================== + + * Drop partial bytes on all parsed units + * Fix non-finite numbers to `.format` to return `null` + * Fix parsing byte string that looks like hex + * perf: hoist regular expressions + +2.2.0 / 2015-11-13 +================== + + * add option "decimalPlaces" + * add option "fixedDecimals" + +2.1.0 / 2015-05-21 +================== + + * add `.format` export + * add `.parse` export + +2.0.2 / 2015-05-20 +================== + + * remove map recreation + * remove unnecessary object construction + +2.0.1 / 2015-05-07 +================== + + * fix browserify require + * remove node.extend dependency + +2.0.0 / 2015-04-12 +================== + + * add option "case" + * add option "thousandsSeparator" + * return "null" on invalid parse input + * support proper round-trip: bytes(bytes(num)) === num + * units no longer case sensitive when parsing + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/node_modules/bytes/LICENSE b/node_modules/bytes/LICENSE new file mode 100644 index 0000000..63e95a9 --- /dev/null +++ b/node_modules/bytes/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015 Jed Watson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/bytes/Readme.md b/node_modules/bytes/Readme.md new file mode 100644 index 0000000..5790e23 --- /dev/null +++ b/node_modules/bytes/Readme.md @@ -0,0 +1,152 @@ +# Bytes utility + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install bytes +``` + +## Usage + +```js +var bytes = require('bytes'); +``` + +#### bytes(number|string value, [options]): number|string|null + +Default export function. Delegates to either `bytes.format` or `bytes.parse` based on the type of `value`. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number`|`string` | Number value to format or string value to parse | +| options | `Object` | Conversion options for `format` | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`number`|`null` | Return null upon error. Numeric value in bytes, or string value otherwise. | + +**Example** + +```js +bytes(1024); +// output: '1KB' + +bytes('1KB'); +// output: 1024 +``` + +#### bytes.format(number value, [options]): string|null + +Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is + rounded. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number` | Value in bytes | +| options | `Object` | Conversion options | + +**Options** + +| Property | Type | Description | +|-------------------|--------|-----------------------------------------------------------------------------------------| +| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | +| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | +| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `'.'`... Default value to `''`. | +| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). | +| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`null` | Return null upon error. String value otherwise. | + +**Example** + +```js +bytes.format(1024); +// output: '1KB' + +bytes.format(1000); +// output: '1000B' + +bytes.format(1000, {thousandsSeparator: ' '}); +// output: '1 000B' + +bytes.format(1024 * 1.7, {decimalPlaces: 0}); +// output: '2KB' + +bytes.format(1024, {unitSeparator: ' '}); +// output: '1 KB' +``` + +#### bytes.parse(string|number value): number|null + +Parse the string value into an integer in bytes. If no unit is given, or `value` +is a number, it is assumed the value is in bytes. + +Supported units and abbreviations are as follows and are case-insensitive: + + * `b` for bytes + * `kb` for kilobytes + * `mb` for megabytes + * `gb` for gigabytes + * `tb` for terabytes + * `pb` for petabytes + +The units are in powers of two, not ten. This means 1kb = 1024b according to this parser. + +**Arguments** + +| Name | Type | Description | +|---------------|--------|--------------------| +| value | `string`|`number` | String to parse, or number in bytes. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | + +**Example** + +```js +bytes.parse('1KB'); +// output: 1024 + +bytes.parse('1024'); +// output: 1024 + +bytes.parse(1024); +// output: 1024 +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/visionmedia/bytes.js/master?label=ci +[ci-url]: https://github.com/visionmedia/bytes.js/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/visionmedia/bytes.js/master +[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master +[downloads-image]: https://badgen.net/npm/dm/bytes +[downloads-url]: https://npmjs.org/package/bytes +[npm-image]: https://badgen.net/npm/v/bytes +[npm-url]: https://npmjs.org/package/bytes diff --git a/node_modules/bytes/index.js b/node_modules/bytes/index.js new file mode 100644 index 0000000..6f2d0f8 --- /dev/null +++ b/node_modules/bytes/index.js @@ -0,0 +1,170 @@ +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; + +/** + * Module variables. + * @private + */ + +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), +}; + +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; + +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ + +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } + + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; + + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.pb) { + unit = 'PB'; + } else if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; + } + } + + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } + + if (thousandsSeparator) { + str = str.split('.').map(function (s, i) { + return i === 0 + ? s.replace(formatThousandsRegExp, thousandsSeparator) + : s + }).join('.'); + } + + return str + unitSeparator + unit; +} + +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ + +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } + + if (typeof val !== 'string') { + return null; + } + + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; + + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + if (isNaN(floatValue)) { + return null; + } + + return Math.floor(map[unit] * floatValue); +} diff --git a/node_modules/bytes/package.json b/node_modules/bytes/package.json new file mode 100644 index 0000000..f2b6a8b --- /dev/null +++ b/node_modules/bytes/package.json @@ -0,0 +1,42 @@ +{ + "name": "bytes", + "description": "Utility to parse a string bytes to bytes and vice-versa", + "version": "3.1.2", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Jed Watson ", + "Théo FIDRY " + ], + "license": "MIT", + "keywords": [ + "byte", + "bytes", + "utility", + "parse", + "parser", + "convert", + "converter" + ], + "repository": "visionmedia/bytes.js", + "devDependencies": { + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "History.md", + "LICENSE", + "Readme.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --check-leaks --reporter spec", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/call-bind-apply-helpers/.eslintrc b/node_modules/call-bind-apply-helpers/.eslintrc new file mode 100644 index 0000000..201e859 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + "no-extra-parens": 0, + "no-magic-numbers": 0, + }, +} diff --git a/node_modules/call-bind-apply-helpers/.github/FUNDING.yml b/node_modules/call-bind-apply-helpers/.github/FUNDING.yml new file mode 100644 index 0000000..0011e9d --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bind-apply-helpers +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/call-bind-apply-helpers/.nycrc b/node_modules/call-bind-apply-helpers/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/call-bind-apply-helpers/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/call-bind-apply-helpers/CHANGELOG.md b/node_modules/call-bind-apply-helpers/CHANGELOG.md new file mode 100644 index 0000000..2484942 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/CHANGELOG.md @@ -0,0 +1,30 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.1...v1.0.2) - 2025-02-12 + +### Commits + +- [types] improve inferred types [`e6f9586`](https://github.com/ljharb/call-bind-apply-helpers/commit/e6f95860a3c72879cb861a858cdfb8138fbedec1) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`e43d540`](https://github.com/ljharb/call-bind-apply-helpers/commit/e43d5409f97543bfbb11f345d47d8ce4e066d8c1) + +## [v1.0.1](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.0...v1.0.1) - 2024-12-08 + +### Commits + +- [types] `reflectApply`: fix types [`4efc396`](https://github.com/ljharb/call-bind-apply-helpers/commit/4efc3965351a4f02cc55e836fa391d3d11ef2ef8) +- [Fix] `reflectApply`: oops, Reflect is not a function [`83cc739`](https://github.com/ljharb/call-bind-apply-helpers/commit/83cc7395de6b79b7730bdf092f1436f0b1263c75) +- [Dev Deps] update `@arethetypeswrong/cli` [`80bd5d3`](https://github.com/ljharb/call-bind-apply-helpers/commit/80bd5d3ae58b4f6b6995ce439dd5a1bcb178a940) + +## v1.0.0 - 2024-12-05 + +### Commits + +- Initial implementation, tests, readme [`7879629`](https://github.com/ljharb/call-bind-apply-helpers/commit/78796290f9b7430c9934d6f33d94ae9bc89fce04) +- Initial commit [`3f1dc16`](https://github.com/ljharb/call-bind-apply-helpers/commit/3f1dc164afc43285631b114a5f9dd9137b2b952f) +- npm init [`081df04`](https://github.com/ljharb/call-bind-apply-helpers/commit/081df048c312fcee400922026f6e97281200a603) +- Only apps should have lockfiles [`5b9ca0f`](https://github.com/ljharb/call-bind-apply-helpers/commit/5b9ca0fe8101ebfaf309c549caac4e0a017ed930) diff --git a/node_modules/call-bind-apply-helpers/LICENSE b/node_modules/call-bind-apply-helpers/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/call-bind-apply-helpers/README.md b/node_modules/call-bind-apply-helpers/README.md new file mode 100644 index 0000000..8fc0dae --- /dev/null +++ b/node_modules/call-bind-apply-helpers/README.md @@ -0,0 +1,62 @@ +# call-bind-apply-helpers [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Helper functions around Function call/apply/bind, for use in `call-bind`. + +The only packages that should likely ever use this package directly are `call-bind` and `get-intrinsic`. +Please use `call-bind` unless you have a very good reason not to. + +## Getting started + +```sh +npm install --save call-bind-apply-helpers +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBindBasic = require('call-bind-apply-helpers'); + +function f(a, b) { + assert.equal(this, 1); + assert.equal(a, 2); + assert.equal(b, 3); + assert.equal(arguments.length, 2); +} + +const fBound = callBindBasic([f, 1]); + +delete Function.prototype.call; +delete Function.prototype.bind; + +fBound(2, 3); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bind-apply-helpers +[npm-version-svg]: https://versionbadg.es/ljharb/call-bind-apply-helpers.svg +[deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers.svg +[deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers +[dev-deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bind-apply-helpers.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bind-apply-helpers.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bind-apply-helpers.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bind-apply-helpers +[codecov-image]: https://codecov.io/gh/ljharb/call-bind-apply-helpers/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bind-apply-helpers/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bind-apply-helpers +[actions-url]: https://github.com/ljharb/call-bind-apply-helpers/actions diff --git a/node_modules/call-bind-apply-helpers/actualApply.d.ts b/node_modules/call-bind-apply-helpers/actualApply.d.ts new file mode 100644 index 0000000..b87286a --- /dev/null +++ b/node_modules/call-bind-apply-helpers/actualApply.d.ts @@ -0,0 +1 @@ +export = Reflect.apply; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/actualApply.js b/node_modules/call-bind-apply-helpers/actualApply.js new file mode 100644 index 0000000..ffa5135 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/actualApply.js @@ -0,0 +1,10 @@ +'use strict'; + +var bind = require('function-bind'); + +var $apply = require('./functionApply'); +var $call = require('./functionCall'); +var $reflectApply = require('./reflectApply'); + +/** @type {import('./actualApply')} */ +module.exports = $reflectApply || bind.call($call, $apply); diff --git a/node_modules/call-bind-apply-helpers/applyBind.d.ts b/node_modules/call-bind-apply-helpers/applyBind.d.ts new file mode 100644 index 0000000..d176c1a --- /dev/null +++ b/node_modules/call-bind-apply-helpers/applyBind.d.ts @@ -0,0 +1,19 @@ +import actualApply from './actualApply'; + +type TupleSplitHead = T['length'] extends N + ? T + : T extends [...infer R, any] + ? TupleSplitHead + : never + +type TupleSplitTail = O['length'] extends N + ? T + : T extends [infer F, ...infer R] + ? TupleSplitTail<[...R], N, [...O, F]> + : never + +type TupleSplit = [TupleSplitHead, TupleSplitTail] + +declare function applyBind(...args: TupleSplit, 2>[1]): ReturnType; + +export = applyBind; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/applyBind.js b/node_modules/call-bind-apply-helpers/applyBind.js new file mode 100644 index 0000000..d2b7723 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/applyBind.js @@ -0,0 +1,10 @@ +'use strict'; + +var bind = require('function-bind'); +var $apply = require('./functionApply'); +var actualApply = require('./actualApply'); + +/** @type {import('./applyBind')} */ +module.exports = function applyBind() { + return actualApply(bind, $apply, arguments); +}; diff --git a/node_modules/call-bind-apply-helpers/functionApply.d.ts b/node_modules/call-bind-apply-helpers/functionApply.d.ts new file mode 100644 index 0000000..1f6e11b --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionApply.d.ts @@ -0,0 +1 @@ +export = Function.prototype.apply; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/functionApply.js b/node_modules/call-bind-apply-helpers/functionApply.js new file mode 100644 index 0000000..c71df9c --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionApply.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./functionApply')} */ +module.exports = Function.prototype.apply; diff --git a/node_modules/call-bind-apply-helpers/functionCall.d.ts b/node_modules/call-bind-apply-helpers/functionCall.d.ts new file mode 100644 index 0000000..15e93df --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionCall.d.ts @@ -0,0 +1 @@ +export = Function.prototype.call; \ No newline at end of file diff --git a/node_modules/call-bind-apply-helpers/functionCall.js b/node_modules/call-bind-apply-helpers/functionCall.js new file mode 100644 index 0000000..7a8d873 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/functionCall.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./functionCall')} */ +module.exports = Function.prototype.call; diff --git a/node_modules/call-bind-apply-helpers/index.d.ts b/node_modules/call-bind-apply-helpers/index.d.ts new file mode 100644 index 0000000..541516b --- /dev/null +++ b/node_modules/call-bind-apply-helpers/index.d.ts @@ -0,0 +1,64 @@ +type RemoveFromTuple< + Tuple extends readonly unknown[], + RemoveCount extends number, + Index extends 1[] = [] +> = Index["length"] extends RemoveCount + ? Tuple + : Tuple extends [infer First, ...infer Rest] + ? RemoveFromTuple + : Tuple; + +type ConcatTuples< + Prefix extends readonly unknown[], + Suffix extends readonly unknown[] +> = [...Prefix, ...Suffix]; + +type ExtractFunctionParams = T extends (this: infer TThis, ...args: infer P extends readonly unknown[]) => infer R + ? { thisArg: TThis; params: P; returnType: R } + : never; + +type BindFunction< + T extends (this: any, ...args: any[]) => any, + TThis, + TBoundArgs extends readonly unknown[], + ReceiverBound extends boolean +> = ExtractFunctionParams extends { + thisArg: infer OrigThis; + params: infer P extends readonly unknown[]; + returnType: infer R; +} + ? ReceiverBound extends true + ? (...args: RemoveFromTuple>) => R extends [OrigThis, ...infer Rest] + ? [TThis, ...Rest] // Replace `this` with `thisArg` + : R + : >>( + thisArg: U, + ...args: RemainingArgs + ) => R extends [OrigThis, ...infer Rest] + ? [U, ...ConcatTuples] // Preserve bound args in return type + : R + : never; + +declare function callBind< + const T extends (this: any, ...args: any[]) => any, + Extracted extends ExtractFunctionParams, + const TBoundArgs extends Partial & readonly unknown[], + const TThis extends Extracted["thisArg"] +>( + args: [fn: T, thisArg: TThis, ...boundArgs: TBoundArgs] +): BindFunction; + +declare function callBind< + const T extends (this: any, ...args: any[]) => any, + Extracted extends ExtractFunctionParams, + const TBoundArgs extends Partial & readonly unknown[] +>( + args: [fn: T, ...boundArgs: TBoundArgs] +): BindFunction; + +declare function callBind( + args: [fn: Exclude, ...rest: TArgs] +): never; + +// export as namespace callBind; +export = callBind; diff --git a/node_modules/call-bind-apply-helpers/index.js b/node_modules/call-bind-apply-helpers/index.js new file mode 100644 index 0000000..2f6dab4 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/index.js @@ -0,0 +1,15 @@ +'use strict'; + +var bind = require('function-bind'); +var $TypeError = require('es-errors/type'); + +var $call = require('./functionCall'); +var $actualApply = require('./actualApply'); + +/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ +module.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== 'function') { + throw new $TypeError('a function is required'); + } + return $actualApply(bind, $call, args); +}; diff --git a/node_modules/call-bind-apply-helpers/package.json b/node_modules/call-bind-apply-helpers/package.json new file mode 100644 index 0000000..923b8be --- /dev/null +++ b/node_modules/call-bind-apply-helpers/package.json @@ -0,0 +1,85 @@ +{ + "name": "call-bind-apply-helpers", + "version": "1.0.2", + "description": "Helper functions around Function call/apply/bind, for use in `call-bind`", + "main": "index.js", + "exports": { + ".": "./index.js", + "./actualApply": "./actualApply.js", + "./applyBind": "./applyBind.js", + "./functionApply": "./functionApply.js", + "./functionCall": "./functionCall.js", + "./reflectApply": "./reflectApply.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bind-apply-helpers.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bind-apply-helpers/issues" + }, + "homepage": "https://github.com/ljharb/call-bind-apply-helpers#readme", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.3", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/for-each": "^0.3.3", + "@types/function-bind": "^1.1.10", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "has-strict-mode": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/call-bind-apply-helpers/reflectApply.d.ts b/node_modules/call-bind-apply-helpers/reflectApply.d.ts new file mode 100644 index 0000000..6b2ae76 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/reflectApply.d.ts @@ -0,0 +1,3 @@ +declare const reflectApply: false | typeof Reflect.apply; + +export = reflectApply; diff --git a/node_modules/call-bind-apply-helpers/reflectApply.js b/node_modules/call-bind-apply-helpers/reflectApply.js new file mode 100644 index 0000000..3d03caa --- /dev/null +++ b/node_modules/call-bind-apply-helpers/reflectApply.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./reflectApply')} */ +module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; diff --git a/node_modules/call-bind-apply-helpers/test/index.js b/node_modules/call-bind-apply-helpers/test/index.js new file mode 100644 index 0000000..1cdc89e --- /dev/null +++ b/node_modules/call-bind-apply-helpers/test/index.js @@ -0,0 +1,63 @@ +'use strict'; + +var callBind = require('../'); +var hasStrictMode = require('has-strict-mode')(); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var v = require('es-value-fixtures'); + +var test = require('tape'); + +test('callBindBasic', function (t) { + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + // @ts-expect-error + function () { callBind([nonFunction]); }, + TypeError, + inspect(nonFunction) + ' is not a function' + ); + }); + + var sentinel = { sentinel: true }; + /** @type {(this: T, a: A, b: B) => [T | undefined, A, B]} */ + var func = function (a, b) { + // eslint-disable-next-line no-invalid-this + return [!hasStrictMode && this === global ? undefined : this, a, b]; + }; + t.equal(func.length, 2, 'original function length is 2'); + + /** type {(thisArg: unknown, a: number, b: number) => [unknown, number, number]} */ + var bound = callBind([func]); + /** type {((a: number, b: number) => [typeof sentinel, typeof a, typeof b])} */ + var boundR = callBind([func, sentinel]); + /** type {((b: number) => [typeof sentinel, number, typeof b])} */ + var boundArg = callBind([func, sentinel, /** @type {const} */ (1)]); + + // @ts-expect-error + t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with no args'); + + // @ts-expect-error + t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); + // @ts-expect-error + t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func too few args'); + // @ts-expect-error + t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); + // @ts-expect-error + t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); + + t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); + t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with right args'); + t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); + t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); + + // @ts-expect-error + t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); + // @ts-expect-error + t.deepEqual(bound(1, 2, 3, 4), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args'); + // @ts-expect-error + t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); + // @ts-expect-error + t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); + + t.end(); +}); diff --git a/node_modules/call-bind-apply-helpers/tsconfig.json b/node_modules/call-bind-apply-helpers/tsconfig.json new file mode 100644 index 0000000..aef9993 --- /dev/null +++ b/node_modules/call-bind-apply-helpers/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} \ No newline at end of file diff --git a/node_modules/call-bound/.eslintrc b/node_modules/call-bound/.eslintrc new file mode 100644 index 0000000..2612ed8 --- /dev/null +++ b/node_modules/call-bound/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/call-bound/.github/FUNDING.yml b/node_modules/call-bound/.github/FUNDING.yml new file mode 100644 index 0000000..2a2a135 --- /dev/null +++ b/node_modules/call-bound/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bound +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/call-bound/.nycrc b/node_modules/call-bound/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/call-bound/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/call-bound/CHANGELOG.md b/node_modules/call-bound/CHANGELOG.md new file mode 100644 index 0000000..8bde4e9 --- /dev/null +++ b/node_modules/call-bound/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.4](https://github.com/ljharb/call-bound/compare/v1.0.3...v1.0.4) - 2025-03-03 + +### Commits + +- [types] improve types [`e648922`](https://github.com/ljharb/call-bound/commit/e6489222a9e54f350fbf952ceabe51fd8b6027ff) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`a42a5eb`](https://github.com/ljharb/call-bound/commit/a42a5ebe6c1b54fcdc7997c7dc64fdca9e936719) +- [Deps] update `call-bind-apply-helpers`, `get-intrinsic` [`f529eac`](https://github.com/ljharb/call-bound/commit/f529eac132404c17156bbc23ab2297a25d0f20b8) + +## [v1.0.3](https://github.com/ljharb/call-bound/compare/v1.0.2...v1.0.3) - 2024-12-15 + +### Commits + +- [Refactor] use `call-bind-apply-helpers` instead of `call-bind` [`5e0b134`](https://github.com/ljharb/call-bound/commit/5e0b13496df14fb7d05dae9412f088da8d3f75be) +- [Deps] update `get-intrinsic` [`41fc967`](https://github.com/ljharb/call-bound/commit/41fc96732a22c7b7e8f381f93ccc54bb6293be2e) +- [readme] fix example [`79a0137`](https://github.com/ljharb/call-bound/commit/79a0137723f7c6d09c9c05452bbf8d5efb5d6e49) +- [meta] add `sideEffects` flag [`08b07be`](https://github.com/ljharb/call-bound/commit/08b07be7f1c03f67dc6f3cdaf0906259771859f7) + +## [v1.0.2](https://github.com/ljharb/call-bound/compare/v1.0.1...v1.0.2) - 2024-12-10 + +### Commits + +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `gopd` [`e6a5ffe`](https://github.com/ljharb/call-bound/commit/e6a5ffe849368fe4f74dfd6cdeca1b9baa39e8d5) +- [Deps] update `call-bind`, `get-intrinsic` [`2aeb5b5`](https://github.com/ljharb/call-bound/commit/2aeb5b521dc2b2683d1345c753ea1161de2d1c14) +- [types] improve return type [`1a0c9fe`](https://github.com/ljharb/call-bound/commit/1a0c9fe3114471e7ca1f57d104e2efe713bb4871) + +## v1.0.1 - 2024-12-05 + +### Commits + +- Initial implementation, tests, readme, types [`6d94121`](https://github.com/ljharb/call-bound/commit/6d94121a9243602e506334069f7a03189fe3363d) +- Initial commit [`0eae867`](https://github.com/ljharb/call-bound/commit/0eae867334ea025c33e6e91cdecfc9df96680cf9) +- npm init [`71b2479`](https://github.com/ljharb/call-bound/commit/71b2479c6723e0b7d91a6b663613067e98b7b275) +- Only apps should have lockfiles [`c3754a9`](https://github.com/ljharb/call-bound/commit/c3754a949b7f9132b47e2d18c1729889736741eb) +- [actions] skip `npm ls` in node < 10 [`74275a5`](https://github.com/ljharb/call-bound/commit/74275a5186b8caf6309b6b97472bdcb0df4683a8) +- [Dev Deps] add missing peer dep [`1354de8`](https://github.com/ljharb/call-bound/commit/1354de8679413e4ae9c523d85f76fa7a5e032d97) diff --git a/node_modules/call-bound/LICENSE b/node_modules/call-bound/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/node_modules/call-bound/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/call-bound/README.md b/node_modules/call-bound/README.md new file mode 100644 index 0000000..a44e43e --- /dev/null +++ b/node_modules/call-bound/README.md @@ -0,0 +1,53 @@ +# call-bound [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`. + +## Getting started + +```sh +npm install --save call-bound +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBound = require('call-bound'); + +const slice = callBound('Array.prototype.slice'); + +delete Function.prototype.call; +delete Function.prototype.bind; +delete Array.prototype.slice; + +assert.deepEqual(slice([1, 2, 3, 4], 1, -1), [2, 3]); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bound +[npm-version-svg]: https://versionbadg.es/ljharb/call-bound.svg +[deps-svg]: https://david-dm.org/ljharb/call-bound.svg +[deps-url]: https://david-dm.org/ljharb/call-bound +[dev-deps-svg]: https://david-dm.org/ljharb/call-bound/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bound#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bound.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bound.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bound.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bound +[codecov-image]: https://codecov.io/gh/ljharb/call-bound/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bound/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bound +[actions-url]: https://github.com/ljharb/call-bound/actions diff --git a/node_modules/call-bound/index.d.ts b/node_modules/call-bound/index.d.ts new file mode 100644 index 0000000..5562f00 --- /dev/null +++ b/node_modules/call-bound/index.d.ts @@ -0,0 +1,94 @@ +type Intrinsic = typeof globalThis; + +type IntrinsicName = keyof Intrinsic | `%${keyof Intrinsic}%`; + +type IntrinsicPath = IntrinsicName | `${StripPercents}.${string}` | `%${StripPercents}.${string}%`; + +type AllowMissing = boolean; + +type StripPercents = T extends `%${infer U}%` ? U : T; + +type BindMethodPrecise = + F extends (this: infer This, ...args: infer Args) => infer R + ? (obj: This, ...args: Args) => R + : F extends { + (this: infer This1, ...args: infer Args1): infer R1; + (this: infer This2, ...args: infer Args2): infer R2 + } + ? { + (obj: This1, ...args: Args1): R1; + (obj: This2, ...args: Args2): R2 + } + : never + +// Extract method type from a prototype +type GetPrototypeMethod = + (typeof globalThis)[T] extends { prototype: any } + ? M extends keyof (typeof globalThis)[T]['prototype'] + ? (typeof globalThis)[T]['prototype'][M] + : never + : never + +// Get static property/method +type GetStaticMember = + P extends keyof (typeof globalThis)[T] ? (typeof globalThis)[T][P] : never + +// Type that maps string path to actual bound function or value with better precision +type BoundIntrinsic = + S extends `${infer Obj}.prototype.${infer Method}` + ? Obj extends keyof typeof globalThis + ? BindMethodPrecise> + : unknown + : S extends `${infer Obj}.${infer Prop}` + ? Obj extends keyof typeof globalThis + ? GetStaticMember + : unknown + : unknown + +declare function arraySlice(array: readonly T[], start?: number, end?: number): T[]; +declare function arraySlice(array: ArrayLike, start?: number, end?: number): T[]; +declare function arraySlice(array: IArguments, start?: number, end?: number): T[]; + +// Special cases for methods that need explicit typing +interface SpecialCases { + '%Object.prototype.isPrototypeOf%': (thisArg: {}, obj: unknown) => boolean; + '%String.prototype.replace%': { + (str: string, searchValue: string | RegExp, replaceValue: string): string; + (str: string, searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string + }; + '%Object.prototype.toString%': (obj: {}) => string; + '%Object.prototype.hasOwnProperty%': (obj: {}, v: PropertyKey) => boolean; + '%Array.prototype.slice%': typeof arraySlice; + '%Array.prototype.map%': (array: readonly T[], callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any) => U[]; + '%Array.prototype.filter%': (array: readonly T[], predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any) => T[]; + '%Array.prototype.indexOf%': (array: readonly T[], searchElement: T, fromIndex?: number) => number; + '%Function.prototype.apply%': (fn: (...args: A) => R, thisArg: any, args: A) => R; + '%Function.prototype.call%': (fn: (...args: A) => R, thisArg: any, ...args: A) => R; + '%Function.prototype.bind%': (fn: (...args: A) => R, thisArg: any, ...args: A) => (...remainingArgs: A) => R; + '%Promise.prototype.then%': { + (promise: Promise, onfulfilled: (value: T) => R | PromiseLike): Promise; + (promise: Promise, onfulfilled: ((value: T) => R | PromiseLike) | undefined | null, onrejected: (reason: any) => R | PromiseLike): Promise; + }; + '%RegExp.prototype.test%': (regexp: RegExp, str: string) => boolean; + '%RegExp.prototype.exec%': (regexp: RegExp, str: string) => RegExpExecArray | null; + '%Error.prototype.toString%': (error: Error) => string; + '%TypeError.prototype.toString%': (error: TypeError) => string; + '%String.prototype.split%': ( + obj: unknown, + splitter: string | RegExp | { + [Symbol.split](string: string, limit?: number): string[]; + }, + limit?: number | undefined + ) => string[]; +} + +/** + * Returns a bound function for a prototype method, or a value for a static property. + * + * @param name - The name of the intrinsic (e.g. 'Array.prototype.slice') + * @param {AllowMissing} [allowMissing] - Whether to allow missing intrinsics (default: false) + */ +declare function callBound, S extends IntrinsicPath>(name: K, allowMissing?: AllowMissing): SpecialCases[`%${StripPercents}%`]; +declare function callBound, S extends IntrinsicPath>(name: S, allowMissing?: AllowMissing): BoundIntrinsic; + +export = callBound; diff --git a/node_modules/call-bound/index.js b/node_modules/call-bound/index.js new file mode 100644 index 0000000..e9ade74 --- /dev/null +++ b/node_modules/call-bound/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBindBasic = require('call-bind-apply-helpers'); + +/** @type {(thisArg: string, searchString: string, position?: number) => number} */ +var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); + +/** @type {import('.')} */ +module.exports = function callBoundIntrinsic(name, allowMissing) { + /* eslint no-extra-parens: 0 */ + + var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing)); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBindBasic(/** @type {const} */ ([intrinsic])); + } + return intrinsic; +}; diff --git a/node_modules/call-bound/package.json b/node_modules/call-bound/package.json new file mode 100644 index 0000000..d542db4 --- /dev/null +++ b/node_modules/call-bound/package.json @@ -0,0 +1,99 @@ +{ + "name": "call-bound", + "version": "1.0.4", + "description": "Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bound.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "callbind", + "callbound", + "call", + "bind", + "bound", + "call-bind", + "call-bound", + "function", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bound/issues" + }, + "homepage": "https://github.com/ljharb/call-bound#readme", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.4", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.3.0", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.3", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.5", + "gopd": "^1.2.0", + "has-strict-mode": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/call-bound/test/index.js b/node_modules/call-bound/test/index.js new file mode 100644 index 0000000..a2fc9f0 --- /dev/null +++ b/node_modules/call-bound/test/index.js @@ -0,0 +1,61 @@ +'use strict'; + +var test = require('tape'); + +var callBound = require('../'); + +/** @template {true} T @template U @typedef {T extends U ? T : never} AssertType */ + +test('callBound', function (t) { + // static primitive + t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself'); + t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself'); + + // static non-function object + t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself'); + t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself'); + t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself'); + t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself'); + + // static function + t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself'); + t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself'); + + // prototype primitive + t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself'); + t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself'); + + var x = callBound('Object.prototype.toString'); + var y = callBound('%Object.prototype.toString%'); + + // prototype function + t.notEqual(x, Object.prototype.toString, 'Object.prototype.toString does not yield itself'); + t.notEqual(y, Object.prototype.toString, '%Object.prototype.toString% does not yield itself'); + t.equal(x(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original'); + t.equal(y(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original'); + + t['throws']( + // @ts-expect-error + function () { callBound('does not exist'); }, + SyntaxError, + 'nonexistent intrinsic throws' + ); + t['throws']( + // @ts-expect-error + function () { callBound('does not exist', true); }, + SyntaxError, + 'allowMissing arg still throws for unknown intrinsic' + ); + + t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) { + st['throws']( + function () { callBound('WeakRef'); }, + TypeError, + 'real but absent intrinsic throws' + ); + st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception'); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/call-bound/tsconfig.json b/node_modules/call-bound/tsconfig.json new file mode 100644 index 0000000..8976d98 --- /dev/null +++ b/node_modules/call-bound/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "ESNext", + "lib": ["es2024"], + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/chokidar/LICENSE b/node_modules/chokidar/LICENSE new file mode 100644 index 0000000..fa9162b --- /dev/null +++ b/node_modules/chokidar/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/chokidar/README.md b/node_modules/chokidar/README.md new file mode 100644 index 0000000..8e25dec --- /dev/null +++ b/node_modules/chokidar/README.md @@ -0,0 +1,308 @@ +# Chokidar [![Weekly downloads](https://img.shields.io/npm/dw/chokidar.svg)](https://github.com/paulmillr/chokidar) [![Yearly downloads](https://img.shields.io/npm/dy/chokidar.svg)](https://github.com/paulmillr/chokidar) + +> Minimal and efficient cross-platform file watching library + +[![NPM](https://nodei.co/npm/chokidar.png)](https://www.npmjs.com/package/chokidar) + +## Why? + +Node.js `fs.watch`: + +* Doesn't report filenames on MacOS. +* Doesn't report events at all when using editors like Sublime on MacOS. +* Often reports events twice. +* Emits most changes as `rename`. +* Does not provide an easy way to recursively watch file trees. +* Does not support recursive watching on Linux. + +Node.js `fs.watchFile`: + +* Almost as bad at event handling. +* Also does not provide any recursive watching. +* Results in high CPU utilization. + +Chokidar resolves these problems. + +Initially made for **[Brunch](https://brunch.io/)** (an ultra-swift web app build tool), it is now used in +[Microsoft's Visual Studio Code](https://github.com/microsoft/vscode), +[gulp](https://github.com/gulpjs/gulp/), +[karma](https://karma-runner.github.io/), +[PM2](https://github.com/Unitech/PM2), +[browserify](http://browserify.org/), +[webpack](https://webpack.github.io/), +[BrowserSync](https://www.browsersync.io/), +and [many others](https://www.npmjs.com/browse/depended/chokidar). +It has proven itself in production environments. + +Version 3 is out! Check out our blog post about it: [Chokidar 3: How to save 32TB of traffic every week](https://paulmillr.com/posts/chokidar-3-save-32tb-of-traffic/) + +## How? + +Chokidar does still rely on the Node.js core `fs` module, but when using +`fs.watch` and `fs.watchFile` for watching, it normalizes the events it +receives, often checking for truth by getting file stats and/or dir contents. + +On MacOS, chokidar by default uses a native extension exposing the Darwin +`FSEvents` API. This provides very efficient recursive watching compared with +implementations like `kqueue` available on most \*nix platforms. Chokidar still +does have to do some work to normalize the events received that way as well. + +On most other platforms, the `fs.watch`-based implementation is the default, which +avoids polling and keeps CPU usage down. Be advised that chokidar will initiate +watchers recursively for everything within scope of the paths that have been +specified, so be judicious about not wasting system resources by watching much +more than needed. + +## Getting started + +Install with npm: + +```sh +npm install chokidar +``` + +Then `require` and use it in your code: + +```javascript +const chokidar = require('chokidar'); + +// One-liner for current directory +chokidar.watch('.').on('all', (event, path) => { + console.log(event, path); +}); +``` + +## API + +```javascript +// Example of a more typical implementation structure + +// Initialize watcher. +const watcher = chokidar.watch('file, dir, glob, or array', { + ignored: /(^|[\/\\])\../, // ignore dotfiles + persistent: true +}); + +// Something to use when events are received. +const log = console.log.bind(console); +// Add event listeners. +watcher + .on('add', path => log(`File ${path} has been added`)) + .on('change', path => log(`File ${path} has been changed`)) + .on('unlink', path => log(`File ${path} has been removed`)); + +// More possible events. +watcher + .on('addDir', path => log(`Directory ${path} has been added`)) + .on('unlinkDir', path => log(`Directory ${path} has been removed`)) + .on('error', error => log(`Watcher error: ${error}`)) + .on('ready', () => log('Initial scan complete. Ready for changes')) + .on('raw', (event, path, details) => { // internal + log('Raw event info:', event, path, details); + }); + +// 'add', 'addDir' and 'change' events also receive stat() results as second +// argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats +watcher.on('change', (path, stats) => { + if (stats) console.log(`File ${path} changed size to ${stats.size}`); +}); + +// Watch new files. +watcher.add('new-file'); +watcher.add(['new-file-2', 'new-file-3', '**/other-file*']); + +// Get list of actual paths being watched on the filesystem +var watchedPaths = watcher.getWatched(); + +// Un-watch some files. +await watcher.unwatch('new-file*'); + +// Stop watching. +// The method is async! +watcher.close().then(() => console.log('closed')); + +// Full list of options. See below for descriptions. +// Do not use this example! +chokidar.watch('file', { + persistent: true, + + ignored: '*.txt', + ignoreInitial: false, + followSymlinks: true, + cwd: '.', + disableGlobbing: false, + + usePolling: false, + interval: 100, + binaryInterval: 300, + alwaysStat: false, + depth: 99, + awaitWriteFinish: { + stabilityThreshold: 2000, + pollInterval: 100 + }, + + ignorePermissionErrors: false, + atomic: true // or a custom 'atomicity delay', in milliseconds (default 100) +}); + +``` + +`chokidar.watch(paths, [options])` + +* `paths` (string or array of strings). Paths to files, dirs to be watched +recursively, or glob patterns. + - Note: globs must not contain windows separators (`\`), + because that's how they work by the standard — + you'll need to replace them with forward slashes (`/`). + - Note 2: for additional glob documentation, check out low-level + library: [picomatch](https://github.com/micromatch/picomatch). +* `options` (object) Options object as defined below: + +#### Persistence + +* `persistent` (default: `true`). Indicates whether the process +should continue to run as long as files are being watched. If set to +`false` when using `fsevents` to watch, no more events will be emitted +after `ready`, even if the process continues to run. + +#### Path filtering + +* `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition) +Defines files/paths to be ignored. The whole relative or absolute path is +tested, not just filename. If a function with two arguments is provided, it +gets called twice per path - once with a single argument (the path), second +time with two arguments (the path and the +[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) +object of that path). +* `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while +instantiating the watching as chokidar discovers these file paths (before the `ready` event). +* `followSymlinks` (default: `true`). When `false`, only the +symlinks themselves will be watched for changes instead of following +the link references and bubbling events through the link's path. +* `cwd` (no default). The base directory from which watch `paths` are to be +derived. Paths emitted with events will be relative to this. +* `disableGlobbing` (default: `false`). If set to `true` then the strings passed to `.watch()` and `.add()` are treated as +literal path names, even if they look like globs. + +#### Performance + +* `usePolling` (default: `false`). +Whether to use fs.watchFile (backed by polling), or fs.watch. If polling +leads to high CPU utilization, consider setting this to `false`. It is +typically necessary to **set this to `true` to successfully watch files over +a network**, and it may be necessary to successfully watch files in other +non-standard situations. Setting to `true` explicitly on MacOS overrides the +`useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable +to true (1) or false (0) in order to override this option. +* _Polling-specific settings_ (effective when `usePolling: true`) + * `interval` (default: `100`). Interval of file system polling, in milliseconds. You may also + set the CHOKIDAR_INTERVAL env variable to override this option. + * `binaryInterval` (default: `300`). Interval of file system + polling for binary files. + ([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) +* `useFsEvents` (default: `true` on MacOS). Whether to use the +`fsevents` watching interface if available. When set to `true` explicitly +and `fsevents` is available this supercedes the `usePolling` setting. When +set to `false` on MacOS, `usePolling: true` becomes the default. +* `alwaysStat` (default: `false`). If relying upon the +[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) +object that may get passed with `add`, `addDir`, and `change` events, set +this to `true` to ensure it is provided even in cases where it wasn't +already available from the underlying watch events. +* `depth` (default: `undefined`). If set, limits how many levels of +subdirectories will be traversed. +* `awaitWriteFinish` (default: `false`). +By default, the `add` event will fire when a file first appears on disk, before +the entire file has been written. Furthermore, in some cases some `change` +events will be emitted while the file is being written. In some cases, +especially when watching for large files there will be a need to wait for the +write operation to finish before responding to a file creation or modification. +Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size, +holding its `add` and `change` events until the size does not change for a +configurable amount of time. The appropriate duration setting is heavily +dependent on the OS and hardware. For accurate detection this parameter should +be relatively high, making file watching much less responsive. +Use with caution. + * *`options.awaitWriteFinish` can be set to an object in order to adjust + timing params:* + * `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in + milliseconds for a file size to remain constant before emitting its event. + * `awaitWriteFinish.pollInterval` (default: 100). File size polling interval, in milliseconds. + +#### Errors + +* `ignorePermissionErrors` (default: `false`). Indicates whether to watch files +that don't have read permissions if possible. If watching fails due to `EPERM` +or `EACCES` with this set to `true`, the errors will be suppressed silently. +* `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`). +Automatically filters out artifacts that occur when using editors that use +"atomic writes" instead of writing directly to the source file. If a file is +re-added within 100 ms of being deleted, Chokidar emits a `change` event +rather than `unlink` then `add`. If the default of 100 ms does not work well +for you, you can override it by setting `atomic` to a custom value, in +milliseconds. + +### Methods & Events + +`chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`: + +* `.add(path / paths)`: Add files, directories, or glob patterns for tracking. +Takes an array of strings or just one string. +* `.on(event, callback)`: Listen for an FS event. +Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`, +`raw`, `error`. +Additionally `all` is available which gets emitted with the underlying event +name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully. +* `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns. +Takes an array of strings or just one string. +* `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen. +* `.getWatched()`: Returns an object representing all the paths on the file +system being watched by this `FSWatcher` instance. The object's keys are all the +directories (using absolute paths unless the `cwd` option was used), and the +values are arrays of the names of the items contained in each directory. + +## CLI + +If you need a CLI interface for your file watching, check out +[chokidar-cli](https://github.com/open-cli-tools/chokidar-cli), allowing you to +execute a command on each change, or get a stdio stream of change events. + +## Install Troubleshooting + +* `npm WARN optional dep failed, continuing fsevents@n.n.n` + * This message is normal part of how `npm` handles optional dependencies and is + not indicative of a problem. Even if accompanied by other related error messages, + Chokidar should function properly. + +* `TypeError: fsevents is not a constructor` + * Update chokidar by doing `rm -rf node_modules package-lock.json yarn.lock && npm install`, or update your dependency that uses chokidar. + +* Chokidar is producing `ENOSP` error on Linux, like this: + * `bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell` + `Error: watch /home/ ENOSPC` + * This means Chokidar ran out of file handles and you'll need to increase their count by executing the following command in Terminal: + `echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p` + +## Changelog + +For more detailed changelog, see [`full_changelog.md`](.github/full_changelog.md). +- **v3.5 (Jan 6, 2021):** Support for ARM Macs with Apple Silicon. Fixes for deleted symlinks. +- **v3.4 (Apr 26, 2020):** Support for directory-based symlinks. Fixes for macos file replacement. +- **v3.3 (Nov 2, 2019):** `FSWatcher#close()` method became async. That fixes IO race conditions related to close method. +- **v3.2 (Oct 1, 2019):** Improve Linux RAM usage by 50%. Race condition fixes. Windows glob fixes. Improve stability by using tight range of dependency versions. +- **v3.1 (Sep 16, 2019):** dotfiles are no longer filtered out by default. Use `ignored` option if needed. Improve initial Linux scan time by 50%. +- **v3 (Apr 30, 2019):** massive CPU & RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16 and higher. +- **v2 (Dec 29, 2017):** Globs are now posix-style-only; without windows support. Tons of bugfixes. +- **v1 (Apr 7, 2015):** Glob support, symlink support, tons of bugfixes. Node 0.8+ is supported +- **v0.1 (Apr 20, 2012):** Initial release, extracted from [Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66) + +## Also + +Why was chokidar named this way? What's the meaning behind it? + +>Chowkidar is a transliteration of a Hindi word meaning 'watchman, gatekeeper', चौकीदार. This ultimately comes from Sanskrit _ चतुष्क_ (crossway, quadrangle, consisting-of-four). This word is also used in other languages like Urdu as (چوکیدار) which is widely used in Pakistan and India. + +## License + +MIT (c) Paul Miller (), see [LICENSE](LICENSE) file. diff --git a/node_modules/chokidar/index.js b/node_modules/chokidar/index.js new file mode 100644 index 0000000..8752893 --- /dev/null +++ b/node_modules/chokidar/index.js @@ -0,0 +1,973 @@ +'use strict'; + +const { EventEmitter } = require('events'); +const fs = require('fs'); +const sysPath = require('path'); +const { promisify } = require('util'); +const readdirp = require('readdirp'); +const anymatch = require('anymatch').default; +const globParent = require('glob-parent'); +const isGlob = require('is-glob'); +const braces = require('braces'); +const normalizePath = require('normalize-path'); + +const NodeFsHandler = require('./lib/nodefs-handler'); +const FsEventsHandler = require('./lib/fsevents-handler'); +const { + EV_ALL, + EV_READY, + EV_ADD, + EV_CHANGE, + EV_UNLINK, + EV_ADD_DIR, + EV_UNLINK_DIR, + EV_RAW, + EV_ERROR, + + STR_CLOSE, + STR_END, + + BACK_SLASH_RE, + DOUBLE_SLASH_RE, + SLASH_OR_BACK_SLASH_RE, + DOT_RE, + REPLACER_RE, + + SLASH, + SLASH_SLASH, + BRACE_START, + BANG, + ONE_DOT, + TWO_DOTS, + GLOBSTAR, + SLASH_GLOBSTAR, + ANYMATCH_OPTS, + STRING_TYPE, + FUNCTION_TYPE, + EMPTY_STR, + EMPTY_FN, + + isWindows, + isMacos, + isIBMi +} = require('./lib/constants'); + +const stat = promisify(fs.stat); +const readdir = promisify(fs.readdir); + +/** + * @typedef {String} Path + * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName + * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType + */ + +/** + * + * @typedef {Object} WatchHelpers + * @property {Boolean} followSymlinks + * @property {'stat'|'lstat'} statMethod + * @property {Path} path + * @property {Path} watchPath + * @property {Function} entryPath + * @property {Boolean} hasGlob + * @property {Object} globFilter + * @property {Function} filterPath + * @property {Function} filterDir + */ + +const arrify = (value = []) => Array.isArray(value) ? value : [value]; +const flatten = (list, result = []) => { + list.forEach(item => { + if (Array.isArray(item)) { + flatten(item, result); + } else { + result.push(item); + } + }); + return result; +}; + +const unifyPaths = (paths_) => { + /** + * @type {Array} + */ + const paths = flatten(arrify(paths_)); + if (!paths.every(p => typeof p === STRING_TYPE)) { + throw new TypeError(`Non-string provided as watch path: ${paths}`); + } + return paths.map(normalizePathToUnix); +}; + +// If SLASH_SLASH occurs at the beginning of path, it is not replaced +// because "//StoragePC/DrivePool/Movies" is a valid network path +const toUnix = (string) => { + let str = string.replace(BACK_SLASH_RE, SLASH); + let prepend = false; + if (str.startsWith(SLASH_SLASH)) { + prepend = true; + } + while (str.match(DOUBLE_SLASH_RE)) { + str = str.replace(DOUBLE_SLASH_RE, SLASH); + } + if (prepend) { + str = SLASH + str; + } + return str; +}; + +// Our version of upath.normalize +// TODO: this is not equal to path-normalize module - investigate why +const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path))); + +const normalizeIgnored = (cwd = EMPTY_STR) => (path) => { + if (typeof path !== STRING_TYPE) return path; + return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path)); +}; + +const getAbsolutePath = (path, cwd) => { + if (sysPath.isAbsolute(path)) { + return path; + } + if (path.startsWith(BANG)) { + return BANG + sysPath.join(cwd, path.slice(1)); + } + return sysPath.join(cwd, path); +}; + +const undef = (opts, key) => opts[key] === undefined; + +/** + * Directory entry. + * @property {Path} path + * @property {Set} items + */ +class DirEntry { + /** + * @param {Path} dir + * @param {Function} removeWatcher + */ + constructor(dir, removeWatcher) { + this.path = dir; + this._removeWatcher = removeWatcher; + /** @type {Set} */ + this.items = new Set(); + } + + add(item) { + const {items} = this; + if (!items) return; + if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item); + } + + async remove(item) { + const {items} = this; + if (!items) return; + items.delete(item); + if (items.size > 0) return; + + const dir = this.path; + try { + await readdir(dir); + } catch (err) { + if (this._removeWatcher) { + this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir)); + } + } + } + + has(item) { + const {items} = this; + if (!items) return; + return items.has(item); + } + + /** + * @returns {Array} + */ + getChildren() { + const {items} = this; + if (!items) return; + return [...items.values()]; + } + + dispose() { + this.items.clear(); + delete this.path; + delete this._removeWatcher; + delete this.items; + Object.freeze(this); + } +} + +const STAT_METHOD_F = 'stat'; +const STAT_METHOD_L = 'lstat'; +class WatchHelper { + constructor(path, watchPath, follow, fsw) { + this.fsw = fsw; + this.path = path = path.replace(REPLACER_RE, EMPTY_STR); + this.watchPath = watchPath; + this.fullWatchPath = sysPath.resolve(watchPath); + this.hasGlob = watchPath !== path; + /** @type {object|boolean} */ + if (path === EMPTY_STR) this.hasGlob = false; + this.globSymlink = this.hasGlob && follow ? undefined : false; + this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false; + this.dirParts = this.getDirParts(path); + this.dirParts.forEach((parts) => { + if (parts.length > 1) parts.pop(); + }); + this.followSymlinks = follow; + this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; + } + + checkGlobSymlink(entry) { + // only need to resolve once + // first entry should always have entry.parentDir === EMPTY_STR + if (this.globSymlink === undefined) { + this.globSymlink = entry.fullParentDir === this.fullWatchPath ? + false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath}; + } + + if (this.globSymlink) { + return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath); + } + + return entry.fullPath; + } + + entryPath(entry) { + return sysPath.join(this.watchPath, + sysPath.relative(this.watchPath, this.checkGlobSymlink(entry)) + ); + } + + filterPath(entry) { + const {stats} = entry; + if (stats && stats.isSymbolicLink()) return this.filterDir(entry); + const resolvedPath = this.entryPath(entry); + const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ? + this.globFilter(resolvedPath) : true; + return matchesGlob && + this.fsw._isntIgnored(resolvedPath, stats) && + this.fsw._hasReadPermissions(stats); + } + + getDirParts(path) { + if (!this.hasGlob) return []; + const parts = []; + const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path]; + expandedPath.forEach((path) => { + parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE)); + }); + return parts; + } + + filterDir(entry) { + if (this.hasGlob) { + const entryParts = this.getDirParts(this.checkGlobSymlink(entry)); + let globstar = false; + this.unmatchedGlob = !this.dirParts.some((parts) => { + return parts.every((part, i) => { + if (part === GLOBSTAR) globstar = true; + return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS); + }); + }); + } + return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats); + } +} + +/** + * Watches files & directories for changes. Emitted events: + * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` + * + * new FSWatcher() + * .add(directories) + * .on('add', path => log('File', path, 'was added')) + */ +class FSWatcher extends EventEmitter { +// Not indenting methods for history sake; for now. +constructor(_opts) { + super(); + + const opts = {}; + if (_opts) Object.assign(opts, _opts); // for frozen objects + + /** @type {Map} */ + this._watched = new Map(); + /** @type {Map} */ + this._closers = new Map(); + /** @type {Set} */ + this._ignoredPaths = new Set(); + + /** @type {Map} */ + this._throttled = new Map(); + + /** @type {Map} */ + this._symlinkPaths = new Map(); + + this._streams = new Set(); + this.closed = false; + + // Set up default options. + if (undef(opts, 'persistent')) opts.persistent = true; + if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false; + if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false; + if (undef(opts, 'interval')) opts.interval = 100; + if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300; + if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false; + opts.enableBinaryInterval = opts.binaryInterval !== opts.interval; + + // Enable fsevents on OS X when polling isn't explicitly enabled. + if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling; + + // If we can't use fsevents, ensure the options reflect it's disabled. + const canUseFsEvents = FsEventsHandler.canUse(); + if (!canUseFsEvents) opts.useFsEvents = false; + + // Use polling on Mac if not using fsevents. + // Other platforms use non-polling fs_watch. + if (undef(opts, 'usePolling') && !opts.useFsEvents) { + opts.usePolling = isMacos; + } + + // Always default to polling on IBM i because fs.watch() is not available on IBM i. + if(isIBMi) { + opts.usePolling = true; + } + + // Global override (useful for end-developers that need to force polling for all + // instances of chokidar, regardless of usage/dependency depth) + const envPoll = process.env.CHOKIDAR_USEPOLLING; + if (envPoll !== undefined) { + const envLower = envPoll.toLowerCase(); + + if (envLower === 'false' || envLower === '0') { + opts.usePolling = false; + } else if (envLower === 'true' || envLower === '1') { + opts.usePolling = true; + } else { + opts.usePolling = !!envLower; + } + } + const envInterval = process.env.CHOKIDAR_INTERVAL; + if (envInterval) { + opts.interval = Number.parseInt(envInterval, 10); + } + + // Editor atomic write normalization enabled by default with fs.watch + if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents; + if (opts.atomic) this._pendingUnlinks = new Map(); + + if (undef(opts, 'followSymlinks')) opts.followSymlinks = true; + + if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false; + if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {}; + const awf = opts.awaitWriteFinish; + if (awf) { + if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000; + if (!awf.pollInterval) awf.pollInterval = 100; + this._pendingWrites = new Map(); + } + if (opts.ignored) opts.ignored = arrify(opts.ignored); + + let readyCalls = 0; + this._emitReady = () => { + readyCalls++; + if (readyCalls >= this._readyCount) { + this._emitReady = EMPTY_FN; + this._readyEmitted = true; + // use process.nextTick to allow time for listener to be bound + process.nextTick(() => this.emit(EV_READY)); + } + }; + this._emitRaw = (...args) => this.emit(EV_RAW, ...args); + this._readyEmitted = false; + this.options = opts; + + // Initialize with proper watcher. + if (opts.useFsEvents) { + this._fsEventsHandler = new FsEventsHandler(this); + } else { + this._nodeFsHandler = new NodeFsHandler(this); + } + + // You’re frozen when your heart’s not open. + Object.freeze(opts); +} + +// Public methods + +/** + * Adds paths to be watched on an existing FSWatcher instance + * @param {Path|Array} paths_ + * @param {String=} _origAdd private; for handling non-existent paths to be watched + * @param {Boolean=} _internal private; indicates a non-user add + * @returns {FSWatcher} for chaining + */ +add(paths_, _origAdd, _internal) { + const {cwd, disableGlobbing} = this.options; + this.closed = false; + let paths = unifyPaths(paths_); + if (cwd) { + paths = paths.map((path) => { + const absPath = getAbsolutePath(path, cwd); + + // Check `path` instead of `absPath` because the cwd portion can't be a glob + if (disableGlobbing || !isGlob(path)) { + return absPath; + } + return normalizePath(absPath); + }); + } + + // set aside negated glob strings + paths = paths.filter((path) => { + if (path.startsWith(BANG)) { + this._ignoredPaths.add(path.slice(1)); + return false; + } + + // if a path is being added that was previously ignored, stop ignoring it + this._ignoredPaths.delete(path); + this._ignoredPaths.delete(path + SLASH_GLOBSTAR); + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + + return true; + }); + + if (this.options.useFsEvents && this._fsEventsHandler) { + if (!this._readyCount) this._readyCount = paths.length; + if (this.options.persistent) this._readyCount += paths.length; + paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path)); + } else { + if (!this._readyCount) this._readyCount = 0; + this._readyCount += paths.length; + Promise.all( + paths.map(async path => { + const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd); + if (res) this._emitReady(); + return res; + }) + ).then(results => { + if (this.closed) return; + results.filter(item => item).forEach(item => { + this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item)); + }); + }); + } + + return this; +} + +/** + * Close watchers or start ignoring events from specified paths. + * @param {Path|Array} paths_ - string or array of strings, file/directory paths and/or globs + * @returns {FSWatcher} for chaining +*/ +unwatch(paths_) { + if (this.closed) return this; + const paths = unifyPaths(paths_); + const {cwd} = this.options; + + paths.forEach((path) => { + // convert to absolute path unless relative path already matches + if (!sysPath.isAbsolute(path) && !this._closers.has(path)) { + if (cwd) path = sysPath.join(cwd, path); + path = sysPath.resolve(path); + } + + this._closePath(path); + + this._ignoredPaths.add(path); + if (this._watched.has(path)) { + this._ignoredPaths.add(path + SLASH_GLOBSTAR); + } + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + }); + + return this; +} + +/** + * Close watchers and remove all listeners from watched paths. + * @returns {Promise}. +*/ +close() { + if (this.closed) return this._closePromise; + this.closed = true; + + // Memory management. + this.removeAllListeners(); + const closers = []; + this._closers.forEach(closerList => closerList.forEach(closer => { + const promise = closer(); + if (promise instanceof Promise) closers.push(promise); + })); + this._streams.forEach(stream => stream.destroy()); + this._userIgnored = undefined; + this._readyCount = 0; + this._readyEmitted = false; + this._watched.forEach(dirent => dirent.dispose()); + ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => { + this[`_${key}`].clear(); + }); + + this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve(); + return this._closePromise; +} + +/** + * Expose list of watched paths + * @returns {Object} for chaining +*/ +getWatched() { + const watchList = {}; + this._watched.forEach((entry, dir) => { + const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir; + watchList[key || ONE_DOT] = entry.getChildren().sort(); + }); + return watchList; +} + +emitWithAll(event, args) { + this.emit(...args); + if (event !== EV_ERROR) this.emit(EV_ALL, ...args); +} + +// Common helpers +// -------------- + +/** + * Normalize and emit events. + * Calling _emit DOES NOT MEAN emit() would be called! + * @param {EventName} event Type of event + * @param {Path} path File or directory path + * @param {*=} val1 arguments to be passed with event + * @param {*=} val2 + * @param {*=} val3 + * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +async _emit(event, path, val1, val2, val3) { + if (this.closed) return; + + const opts = this.options; + if (isWindows) path = sysPath.normalize(path); + if (opts.cwd) path = sysPath.relative(opts.cwd, path); + /** @type Array */ + const args = [event, path]; + if (val3 !== undefined) args.push(val1, val2, val3); + else if (val2 !== undefined) args.push(val1, val2); + else if (val1 !== undefined) args.push(val1); + + const awf = opts.awaitWriteFinish; + let pw; + if (awf && (pw = this._pendingWrites.get(path))) { + pw.lastChange = new Date(); + return this; + } + + if (opts.atomic) { + if (event === EV_UNLINK) { + this._pendingUnlinks.set(path, args); + setTimeout(() => { + this._pendingUnlinks.forEach((entry, path) => { + this.emit(...entry); + this.emit(EV_ALL, ...entry); + this._pendingUnlinks.delete(path); + }); + }, typeof opts.atomic === 'number' ? opts.atomic : 100); + return this; + } + if (event === EV_ADD && this._pendingUnlinks.has(path)) { + event = args[0] = EV_CHANGE; + this._pendingUnlinks.delete(path); + } + } + + if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) { + const awfEmit = (err, stats) => { + if (err) { + event = args[0] = EV_ERROR; + args[1] = err; + this.emitWithAll(event, args); + } else if (stats) { + // if stats doesn't exist the file must have been deleted + if (args.length > 2) { + args[2] = stats; + } else { + args.push(stats); + } + this.emitWithAll(event, args); + } + }; + + this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit); + return this; + } + + if (event === EV_CHANGE) { + const isThrottled = !this._throttle(EV_CHANGE, path, 50); + if (isThrottled) return this; + } + + if (opts.alwaysStat && val1 === undefined && + (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE) + ) { + const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path; + let stats; + try { + stats = await stat(fullPath); + } catch (err) {} + // Suppress event when fs_stat fails, to avoid sending undefined 'stat' + if (!stats || this.closed) return; + args.push(stats); + } + this.emitWithAll(event, args); + + return this; +} + +/** + * Common handler for errors + * @param {Error} error + * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +_handleError(error) { + const code = error && error.code; + if (error && code !== 'ENOENT' && code !== 'ENOTDIR' && + (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES')) + ) { + this.emit(EV_ERROR, error); + } + return error || this.closed; +} + +/** + * Helper utility for throttling + * @param {ThrottleType} actionType type being throttled + * @param {Path} path being acted upon + * @param {Number} timeout duration of time to suppress duplicate actions + * @returns {Object|false} tracking object or false if action should be suppressed + */ +_throttle(actionType, path, timeout) { + if (!this._throttled.has(actionType)) { + this._throttled.set(actionType, new Map()); + } + + /** @type {Map} */ + const action = this._throttled.get(actionType); + /** @type {Object} */ + const actionPath = action.get(path); + + if (actionPath) { + actionPath.count++; + return false; + } + + let timeoutObject; + const clear = () => { + const item = action.get(path); + const count = item ? item.count : 0; + action.delete(path); + clearTimeout(timeoutObject); + if (item) clearTimeout(item.timeoutObject); + return count; + }; + timeoutObject = setTimeout(clear, timeout); + const thr = {timeoutObject, clear, count: 0}; + action.set(path, thr); + return thr; +} + +_incrReadyCount() { + return this._readyCount++; +} + +/** + * Awaits write operation to finish. + * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. + * @param {Path} path being acted upon + * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished + * @param {EventName} event + * @param {Function} awfEmit Callback to be called when ready for event to be emitted. + */ +_awaitWriteFinish(path, threshold, event, awfEmit) { + let timeoutHandler; + + let fullPath = path; + if (this.options.cwd && !sysPath.isAbsolute(path)) { + fullPath = sysPath.join(this.options.cwd, path); + } + + const now = new Date(); + + const awaitWriteFinish = (prevStat) => { + fs.stat(fullPath, (err, curStat) => { + if (err || !this._pendingWrites.has(path)) { + if (err && err.code !== 'ENOENT') awfEmit(err); + return; + } + + const now = Number(new Date()); + + if (prevStat && curStat.size !== prevStat.size) { + this._pendingWrites.get(path).lastChange = now; + } + const pw = this._pendingWrites.get(path); + const df = now - pw.lastChange; + + if (df >= threshold) { + this._pendingWrites.delete(path); + awfEmit(undefined, curStat); + } else { + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval, + curStat + ); + } + }); + }; + + if (!this._pendingWrites.has(path)) { + this._pendingWrites.set(path, { + lastChange: now, + cancelWait: () => { + this._pendingWrites.delete(path); + clearTimeout(timeoutHandler); + return event; + } + }); + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval + ); + } +} + +_getGlobIgnored() { + return [...this._ignoredPaths.values()]; +} + +/** + * Determines whether user has asked to ignore this path. + * @param {Path} path filepath or dir + * @param {fs.Stats=} stats result of fs.stat + * @returns {Boolean} + */ +_isIgnored(path, stats) { + if (this.options.atomic && DOT_RE.test(path)) return true; + if (!this._userIgnored) { + const {cwd} = this.options; + const ign = this.options.ignored; + + const ignored = ign && ign.map(normalizeIgnored(cwd)); + const paths = arrify(ignored) + .filter((path) => typeof path === STRING_TYPE && !isGlob(path)) + .map((path) => path + SLASH_GLOBSTAR); + const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths); + this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS); + } + + return this._userIgnored([path, stats]); +} + +_isntIgnored(path, stat) { + return !this._isIgnored(path, stat); +} + +/** + * Provides a set of common helpers and properties relating to symlink and glob handling. + * @param {Path} path file, directory, or glob pattern being watched + * @param {Number=} depth at any depth > 0, this isn't a glob + * @returns {WatchHelper} object containing helpers for this path + */ +_getWatchHelpers(path, depth) { + const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path); + const follow = this.options.followSymlinks; + + return new WatchHelper(path, watchPath, follow, this); +} + +// Directory helpers +// ----------------- + +/** + * Provides directory tracking objects + * @param {String} directory path of the directory + * @returns {DirEntry} the directory's tracking object + */ +_getWatchedDir(directory) { + if (!this._boundRemove) this._boundRemove = this._remove.bind(this); + const dir = sysPath.resolve(directory); + if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove)); + return this._watched.get(dir); +} + +// File helpers +// ------------ + +/** + * Check for read permissions. + * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405 + * @param {fs.Stats} stats - object, result of fs_stat + * @returns {Boolean} indicates whether the file can be read +*/ +_hasReadPermissions(stats) { + if (this.options.ignorePermissionErrors) return true; + + // stats.mode may be bigint + const md = stats && Number.parseInt(stats.mode, 10); + const st = md & 0o777; + const it = Number.parseInt(st.toString(8)[0], 10); + return Boolean(4 & it); +} + +/** + * Handles emitting unlink events for + * files and directories, and via recursion, for + * files and directories within directories that are unlinked + * @param {String} directory within which the following item is located + * @param {String} item base path of item/directory + * @returns {void} +*/ +_remove(directory, item, isDirectory) { + // if what is being deleted is a directory, get that directory's paths + // for recursive deleting and cleaning of watched object + // if it is not a directory, nestedDirectoryChildren will be empty array + const path = sysPath.join(directory, item); + const fullPath = sysPath.resolve(path); + isDirectory = isDirectory != null + ? isDirectory + : this._watched.has(path) || this._watched.has(fullPath); + + // prevent duplicate handling in case of arriving here nearly simultaneously + // via multiple paths (such as _handleFile and _handleDir) + if (!this._throttle('remove', path, 100)) return; + + // if the only watched file is removed, watch for its return + if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) { + this.add(directory, item, true); + } + + // This will create a new entry in the watched object in either case + // so we got to do the directory check beforehand + const wp = this._getWatchedDir(path); + const nestedDirectoryChildren = wp.getChildren(); + + // Recursively remove children directories / files. + nestedDirectoryChildren.forEach(nested => this._remove(path, nested)); + + // Check if item was on the watched list and remove it + const parent = this._getWatchedDir(directory); + const wasTracked = parent.has(item); + parent.remove(item); + + // Fixes issue #1042 -> Relative paths were detected and added as symlinks + // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612), + // but never removed from the map in case the path was deleted. + // This leads to an incorrect state if the path was recreated: + // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553 + if (this._symlinkPaths.has(fullPath)) { + this._symlinkPaths.delete(fullPath); + } + + // If we wait for this file to be fully written, cancel the wait. + let relPath = path; + if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path); + if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { + const event = this._pendingWrites.get(relPath).cancelWait(); + if (event === EV_ADD) return; + } + + // The Entry will either be a directory that just got removed + // or a bogus entry to a file, in either case we have to remove it + this._watched.delete(path); + this._watched.delete(fullPath); + const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK; + if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path); + + // Avoid conflicts if we later create another file with the same name + if (!this.options.useFsEvents) { + this._closePath(path); + } +} + +/** + * Closes all watchers for a path + * @param {Path} path + */ +_closePath(path) { + this._closeFile(path) + const dir = sysPath.dirname(path); + this._getWatchedDir(dir).remove(sysPath.basename(path)); +} + +/** + * Closes only file-specific watchers + * @param {Path} path + */ +_closeFile(path) { + const closers = this._closers.get(path); + if (!closers) return; + closers.forEach(closer => closer()); + this._closers.delete(path); +} + +/** + * + * @param {Path} path + * @param {Function} closer + */ +_addPathCloser(path, closer) { + if (!closer) return; + let list = this._closers.get(path); + if (!list) { + list = []; + this._closers.set(path, list); + } + list.push(closer); +} + +_readdirp(root, opts) { + if (this.closed) return; + const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts}; + let stream = readdirp(root, options); + this._streams.add(stream); + stream.once(STR_CLOSE, () => { + stream = undefined; + }); + stream.once(STR_END, () => { + if (stream) { + this._streams.delete(stream); + stream = undefined; + } + }); + return stream; +} + +} + +// Export FSWatcher class +exports.FSWatcher = FSWatcher; + +/** + * Instantiates watcher with paths to be tracked. + * @param {String|Array} paths file/directory paths and/or globs + * @param {Object=} options chokidar opts + * @returns an instance of FSWatcher for chaining. + */ +const watch = (paths, options) => { + const watcher = new FSWatcher(options); + watcher.add(paths); + return watcher; +}; + +exports.watch = watch; diff --git a/node_modules/chokidar/lib/constants.js b/node_modules/chokidar/lib/constants.js new file mode 100644 index 0000000..4743865 --- /dev/null +++ b/node_modules/chokidar/lib/constants.js @@ -0,0 +1,66 @@ +'use strict'; + +const {sep} = require('path'); +const {platform} = process; +const os = require('os'); + +exports.EV_ALL = 'all'; +exports.EV_READY = 'ready'; +exports.EV_ADD = 'add'; +exports.EV_CHANGE = 'change'; +exports.EV_ADD_DIR = 'addDir'; +exports.EV_UNLINK = 'unlink'; +exports.EV_UNLINK_DIR = 'unlinkDir'; +exports.EV_RAW = 'raw'; +exports.EV_ERROR = 'error'; + +exports.STR_DATA = 'data'; +exports.STR_END = 'end'; +exports.STR_CLOSE = 'close'; + +exports.FSEVENT_CREATED = 'created'; +exports.FSEVENT_MODIFIED = 'modified'; +exports.FSEVENT_DELETED = 'deleted'; +exports.FSEVENT_MOVED = 'moved'; +exports.FSEVENT_CLONED = 'cloned'; +exports.FSEVENT_UNKNOWN = 'unknown'; +exports.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1; +exports.FSEVENT_TYPE_FILE = 'file'; +exports.FSEVENT_TYPE_DIRECTORY = 'directory'; +exports.FSEVENT_TYPE_SYMLINK = 'symlink'; + +exports.KEY_LISTENERS = 'listeners'; +exports.KEY_ERR = 'errHandlers'; +exports.KEY_RAW = 'rawEmitters'; +exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW]; + +exports.DOT_SLASH = `.${sep}`; + +exports.BACK_SLASH_RE = /\\/g; +exports.DOUBLE_SLASH_RE = /\/\//; +exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/; +exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; +exports.REPLACER_RE = /^\.[/\\]/; + +exports.SLASH = '/'; +exports.SLASH_SLASH = '//'; +exports.BRACE_START = '{'; +exports.BANG = '!'; +exports.ONE_DOT = '.'; +exports.TWO_DOTS = '..'; +exports.STAR = '*'; +exports.GLOBSTAR = '**'; +exports.ROOT_GLOBSTAR = '/**/*'; +exports.SLASH_GLOBSTAR = '/**'; +exports.DIR_SUFFIX = 'Dir'; +exports.ANYMATCH_OPTS = {dot: true}; +exports.STRING_TYPE = 'string'; +exports.FUNCTION_TYPE = 'function'; +exports.EMPTY_STR = ''; +exports.EMPTY_FN = () => {}; +exports.IDENTITY_FN = val => val; + +exports.isWindows = platform === 'win32'; +exports.isMacos = platform === 'darwin'; +exports.isLinux = platform === 'linux'; +exports.isIBMi = os.type() === 'OS400'; diff --git a/node_modules/chokidar/lib/fsevents-handler.js b/node_modules/chokidar/lib/fsevents-handler.js new file mode 100644 index 0000000..fe29393 --- /dev/null +++ b/node_modules/chokidar/lib/fsevents-handler.js @@ -0,0 +1,526 @@ +'use strict'; + +const fs = require('fs'); +const sysPath = require('path'); +const { promisify } = require('util'); + +let fsevents; +try { + fsevents = require('fsevents'); +} catch (error) { + if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error); +} + +if (fsevents) { + // TODO: real check + const mtch = process.version.match(/v(\d+)\.(\d+)/); + if (mtch && mtch[1] && mtch[2]) { + const maj = Number.parseInt(mtch[1], 10); + const min = Number.parseInt(mtch[2], 10); + if (maj === 8 && min < 16) { + fsevents = undefined; + } + } +} + +const { + EV_ADD, + EV_CHANGE, + EV_ADD_DIR, + EV_UNLINK, + EV_ERROR, + STR_DATA, + STR_END, + FSEVENT_CREATED, + FSEVENT_MODIFIED, + FSEVENT_DELETED, + FSEVENT_MOVED, + // FSEVENT_CLONED, + FSEVENT_UNKNOWN, + FSEVENT_FLAG_MUST_SCAN_SUBDIRS, + FSEVENT_TYPE_FILE, + FSEVENT_TYPE_DIRECTORY, + FSEVENT_TYPE_SYMLINK, + + ROOT_GLOBSTAR, + DIR_SUFFIX, + DOT_SLASH, + FUNCTION_TYPE, + EMPTY_FN, + IDENTITY_FN +} = require('./constants'); + +const Depth = (value) => isNaN(value) ? {} : {depth: value}; + +const stat = promisify(fs.stat); +const lstat = promisify(fs.lstat); +const realpath = promisify(fs.realpath); + +const statMethods = { stat, lstat }; + +/** + * @typedef {String} Path + */ + +/** + * @typedef {Object} FsEventsWatchContainer + * @property {Set} listeners + * @property {Function} rawEmitter + * @property {{stop: Function}} watcher + */ + +// fsevents instance helper functions +/** + * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances) + * @type {Map} + */ +const FSEventsWatchers = new Map(); + +// Threshold of duplicate path prefixes at which to start +// consolidating going forward +const consolidateThreshhold = 10; + +const wrongEventFlags = new Set([ + 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912 +]); + +/** + * Instantiates the fsevents interface + * @param {Path} path path to be watched + * @param {Function} callback called when fsevents is bound and ready + * @returns {{stop: Function}} new fsevents instance + */ +const createFSEventsInstance = (path, callback) => { + const stop = fsevents.watch(path, callback); + return {stop}; +}; + +/** + * Instantiates the fsevents interface or binds listeners to an existing one covering + * the same file tree. + * @param {Path} path - to be watched + * @param {Path} realPath - real path for symlinks + * @param {Function} listener - called when fsevents emits events + * @param {Function} rawEmitter - passes data to listeners of the 'raw' event + * @returns {Function} closer + */ +function setFSEventsListener(path, realPath, listener, rawEmitter) { + let watchPath = sysPath.extname(realPath) ? sysPath.dirname(realPath) : realPath; + + const parentPath = sysPath.dirname(watchPath); + let cont = FSEventsWatchers.get(watchPath); + + // If we've accumulated a substantial number of paths that + // could have been consolidated by watching one directory + // above the current one, create a watcher on the parent + // path instead, so that we do consolidate going forward. + if (couldConsolidate(parentPath)) { + watchPath = parentPath; + } + + const resolvedPath = sysPath.resolve(path); + const hasSymlink = resolvedPath !== realPath; + + const filteredListener = (fullPath, flags, info) => { + if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath); + if ( + fullPath === resolvedPath || + !fullPath.indexOf(resolvedPath + sysPath.sep) + ) listener(fullPath, flags, info); + }; + + // check if there is already a watcher on a parent path + // modifies `watchPath` to the parent path when it finds a match + let watchedParent = false; + for (const watchedPath of FSEventsWatchers.keys()) { + if (realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep) === 0) { + watchPath = watchedPath; + cont = FSEventsWatchers.get(watchPath); + watchedParent = true; + break; + } + } + + if (cont || watchedParent) { + cont.listeners.add(filteredListener); + } else { + cont = { + listeners: new Set([filteredListener]), + rawEmitter, + watcher: createFSEventsInstance(watchPath, (fullPath, flags) => { + if (!cont.listeners.size) return; + if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return; + const info = fsevents.getInfo(fullPath, flags); + cont.listeners.forEach(list => { + list(fullPath, flags, info); + }); + + cont.rawEmitter(info.event, fullPath, info); + }) + }; + FSEventsWatchers.set(watchPath, cont); + } + + // removes this instance's listeners and closes the underlying fsevents + // instance if there are no more listeners left + return () => { + const lst = cont.listeners; + + lst.delete(filteredListener); + if (!lst.size) { + FSEventsWatchers.delete(watchPath); + if (cont.watcher) return cont.watcher.stop().then(() => { + cont.rawEmitter = cont.watcher = undefined; + Object.freeze(cont); + }); + } + }; +} + +// Decide whether or not we should start a new higher-level +// parent watcher +const couldConsolidate = (path) => { + let count = 0; + for (const watchPath of FSEventsWatchers.keys()) { + if (watchPath.indexOf(path) === 0) { + count++; + if (count >= consolidateThreshhold) { + return true; + } + } + } + + return false; +}; + +// returns boolean indicating whether fsevents can be used +const canUse = () => fsevents && FSEventsWatchers.size < 128; + +// determines subdirectory traversal levels from root to path +const calcDepth = (path, root) => { + let i = 0; + while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++; + return i; +}; + +// returns boolean indicating whether the fsevents' event info has the same type +// as the one returned by fs.stat +const sameTypes = (info, stats) => ( + info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() || + info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() || + info.type === FSEVENT_TYPE_FILE && stats.isFile() +) + +/** + * @mixin + */ +class FsEventsHandler { + +/** + * @param {import('../index').FSWatcher} fsw + */ +constructor(fsw) { + this.fsw = fsw; +} +checkIgnored(path, stats) { + const ipaths = this.fsw._ignoredPaths; + if (this.fsw._isIgnored(path, stats)) { + ipaths.add(path); + if (stats && stats.isDirectory()) { + ipaths.add(path + ROOT_GLOBSTAR); + } + return true; + } + + ipaths.delete(path); + ipaths.delete(path + ROOT_GLOBSTAR); +} + +addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD; + this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts); +} + +async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + try { + const stats = await stat(path) + if (this.fsw.closed) return; + if (sameTypes(info, stats)) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } catch (error) { + if (error.code === 'EACCES') { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } +} + +handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) { + if (this.fsw.closed || this.checkIgnored(path)) return; + + if (event === EV_UNLINK) { + const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY + // suppress unlink events on never before seen files + if (isDirectory || watchedDir.has(item)) { + this.fsw._remove(parent, item, isDirectory); + } + } else { + if (event === EV_ADD) { + // track new directories + if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path); + + if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) { + // push symlinks back to the top of the stack to get handled + const curDepth = opts.depth === undefined ? + undefined : calcDepth(fullPath, realPath) + 1; + return this._addToFsEvents(path, false, true, curDepth); + } + + // track new paths + // (other than symlinks being followed, which will be tracked soon) + this.fsw._getWatchedDir(parent).add(item); + } + /** + * @type {'add'|'addDir'|'unlink'|'unlinkDir'} + */ + const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event; + this.fsw._emit(eventName, path); + if (eventName === EV_ADD_DIR) this._addToFsEvents(path, false, true); + } +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} watchPath - file/dir path to be watched with fsevents + * @param {String} realPath - real path (in case of symlinks) + * @param {Function} transform - path transformer + * @param {Function} globFilter - path filter in case a glob pattern was provided + * @returns {Function} closer for the watcher instance +*/ +_watchWithFsEvents(watchPath, realPath, transform, globFilter) { + if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return; + const opts = this.fsw.options; + const watchCallback = async (fullPath, flags, info) => { + if (this.fsw.closed) return; + if ( + opts.depth !== undefined && + calcDepth(fullPath, realPath) > opts.depth + ) return; + const path = transform(sysPath.join( + watchPath, sysPath.relative(watchPath, fullPath) + )); + if (globFilter && !globFilter(path)) return; + // ensure directories are tracked + const parent = sysPath.dirname(path); + const item = sysPath.basename(path); + const watchedDir = this.fsw._getWatchedDir( + info.type === FSEVENT_TYPE_DIRECTORY ? path : parent + ); + + // correct for wrong events emitted + if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) { + if (typeof opts.ignored === FUNCTION_TYPE) { + let stats; + try { + stats = await stat(path); + } catch (error) {} + if (this.fsw.closed) return; + if (this.checkIgnored(path, stats)) return; + if (sameTypes(info, stats)) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + switch (info.event) { + case FSEVENT_CREATED: + case FSEVENT_MODIFIED: + return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + case FSEVENT_DELETED: + case FSEVENT_MOVED: + return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } + }; + + const closer = setFSEventsListener( + watchPath, + realPath, + watchCallback, + this.fsw._emitRaw + ); + + this.fsw._emitReady(); + return closer; +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} linkPath path to symlink + * @param {String} fullPath absolute path to the symlink + * @param {Function} transform pre-existing path transformer + * @param {Number} curDepth level of subdirectories traversed to where symlink is + * @returns {Promise} + */ +async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) { + // don't follow the same symlink more than once + if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return; + + this.fsw._symlinkPaths.set(fullPath, true); + this.fsw._incrReadyCount(); + + try { + const linkTarget = await realpath(linkPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(linkTarget)) { + return this.fsw._emitReady(); + } + + this.fsw._incrReadyCount(); + + // add the linkTarget for watching with a wrapper for transform + // that causes emitted paths to incorporate the link's path + this._addToFsEvents(linkTarget || linkPath, (path) => { + let aliasedPath = linkPath; + if (linkTarget && linkTarget !== DOT_SLASH) { + aliasedPath = path.replace(linkTarget, linkPath); + } else if (path !== DOT_SLASH) { + aliasedPath = sysPath.join(linkPath, path); + } + return transform(aliasedPath); + }, false, curDepth); + } catch(error) { + if (this.fsw._handleError(error)) { + return this.fsw._emitReady(); + } + } +} + +/** + * + * @param {Path} newPath + * @param {fs.Stats} stats + */ +emitAdd(newPath, stats, processPath, opts, forceAdd) { + const pp = processPath(newPath); + const isDir = stats.isDirectory(); + const dirObj = this.fsw._getWatchedDir(sysPath.dirname(pp)); + const base = sysPath.basename(pp); + + // ensure empty dirs get tracked + if (isDir) this.fsw._getWatchedDir(pp); + if (dirObj.has(base)) return; + dirObj.add(base); + + if (!opts.ignoreInitial || forceAdd === true) { + this.fsw._emit(isDir ? EV_ADD_DIR : EV_ADD, pp, stats); + } +} + +initWatch(realPath, path, wh, processPath) { + if (this.fsw.closed) return; + const closer = this._watchWithFsEvents( + wh.watchPath, + sysPath.resolve(realPath || wh.watchPath), + processPath, + wh.globFilter + ); + this.fsw._addPathCloser(path, closer); +} + +/** + * Handle added path with fsevents + * @param {String} path file/dir path or glob pattern + * @param {Function|Boolean=} transform converts working path to what the user expects + * @param {Boolean=} forceAdd ensure add is emitted + * @param {Number=} priorDepth Level of subdirectories already traversed. + * @returns {Promise} + */ +async _addToFsEvents(path, transform, forceAdd, priorDepth) { + if (this.fsw.closed) { + return; + } + const opts = this.fsw.options; + const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN; + + const wh = this.fsw._getWatchHelpers(path); + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + throw null; + } + if (stats.isDirectory()) { + // emit addDir unless this is a glob parent + if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd); + + // don't recurse further if it would exceed depth setting + if (priorDepth && priorDepth > opts.depth) return; + + // scan the contents of the dir + this.fsw._readdirp(wh.watchPath, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + ...Depth(opts.depth - (priorDepth || 0)) + }).on(STR_DATA, (entry) => { + // need to check filterPath on dirs b/c filterDir is less restrictive + if (this.fsw.closed) { + return; + } + if (entry.stats.isDirectory() && !wh.filterPath(entry)) return; + + const joinedPath = sysPath.join(wh.watchPath, entry.path); + const {fullPath} = entry; + + if (wh.followSymlinks && entry.stats.isSymbolicLink()) { + // preserve the current depth here since it can't be derived from + // real paths past the symlink + const curDepth = opts.depth === undefined ? + undefined : calcDepth(joinedPath, sysPath.resolve(wh.watchPath)) + 1; + + this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth); + } else { + this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd); + } + }).on(EV_ERROR, EMPTY_FN).on(STR_END, () => { + this.fsw._emitReady(); + }); + } else { + this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd); + this.fsw._emitReady(); + } + } catch (error) { + if (!error || this.fsw._handleError(error)) { + // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__- + this.fsw._emitReady(); + this.fsw._emitReady(); + } + } + + if (opts.persistent && forceAdd !== true) { + if (typeof transform === FUNCTION_TYPE) { + // realpath has already been resolved + this.initWatch(undefined, path, wh, processPath); + } else { + let realPath; + try { + realPath = await realpath(wh.watchPath); + } catch (e) {} + this.initWatch(realPath, path, wh, processPath); + } + } +} + +} + +module.exports = FsEventsHandler; +module.exports.canUse = canUse; diff --git a/node_modules/chokidar/lib/nodefs-handler.js b/node_modules/chokidar/lib/nodefs-handler.js new file mode 100644 index 0000000..199cfe9 --- /dev/null +++ b/node_modules/chokidar/lib/nodefs-handler.js @@ -0,0 +1,654 @@ +'use strict'; + +const fs = require('fs'); +const sysPath = require('path'); +const { promisify } = require('util'); +const isBinaryPath = require('is-binary-path'); +const { + isWindows, + isLinux, + EMPTY_FN, + EMPTY_STR, + KEY_LISTENERS, + KEY_ERR, + KEY_RAW, + HANDLER_KEYS, + EV_CHANGE, + EV_ADD, + EV_ADD_DIR, + EV_ERROR, + STR_DATA, + STR_END, + BRACE_START, + STAR +} = require('./constants'); + +const THROTTLE_MODE_WATCH = 'watch'; + +const open = promisify(fs.open); +const stat = promisify(fs.stat); +const lstat = promisify(fs.lstat); +const close = promisify(fs.close); +const fsrealpath = promisify(fs.realpath); + +const statMethods = { lstat, stat }; + +// TODO: emit errors properly. Example: EMFILE on Macos. +const foreach = (val, fn) => { + if (val instanceof Set) { + val.forEach(fn); + } else { + fn(val); + } +}; + +const addAndConvert = (main, prop, item) => { + let container = main[prop]; + if (!(container instanceof Set)) { + main[prop] = container = new Set([container]); + } + container.add(item); +}; + +const clearItem = cont => key => { + const set = cont[key]; + if (set instanceof Set) { + set.clear(); + } else { + delete cont[key]; + } +}; + +const delFromSet = (main, prop, item) => { + const container = main[prop]; + if (container instanceof Set) { + container.delete(item); + } else if (container === item) { + delete main[prop]; + } +}; + +const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; + +/** + * @typedef {String} Path + */ + +// fs_watch helpers + +// object to hold per-process fs_watch instances +// (may be shared across chokidar FSWatcher instances) + +/** + * @typedef {Object} FsWatchContainer + * @property {Set} listeners + * @property {Set} errHandlers + * @property {Set} rawEmitters + * @property {fs.FSWatcher=} watcher + * @property {Boolean=} watcherUnusable + */ + +/** + * @type {Map} + */ +const FsWatchInstances = new Map(); + +/** + * Instantiates the fs_watch interface + * @param {String} path to be watched + * @param {Object} options to be passed to fs_watch + * @param {Function} listener main event handler + * @param {Function} errHandler emits info about errors + * @param {Function} emitRaw emits raw event data + * @returns {fs.FSWatcher} new fsevents instance + */ +function createFsWatchInstance(path, options, listener, errHandler, emitRaw) { + const handleEvent = (rawEvent, evPath) => { + listener(path); + emitRaw(rawEvent, evPath, {watchedPath: path}); + + // emit based on events occurring for files from a directory's watcher in + // case the file's watcher misses it (and rely on throttling to de-dupe) + if (evPath && path !== evPath) { + fsWatchBroadcast( + sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath) + ); + } + }; + try { + return fs.watch(path, options, handleEvent); + } catch (error) { + errHandler(error); + } +} + +/** + * Helper for passing fs_watch event data to a collection of listeners + * @param {Path} fullPath absolute path bound to fs_watch instance + * @param {String} type listener type + * @param {*=} val1 arguments to be passed to listeners + * @param {*=} val2 + * @param {*=} val3 + */ +const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => { + const cont = FsWatchInstances.get(fullPath); + if (!cont) return; + foreach(cont[type], (listener) => { + listener(val1, val2, val3); + }); +}; + +/** + * Instantiates the fs_watch interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path + * @param {String} fullPath absolute path + * @param {Object} options to be passed to fs_watch + * @param {Object} handlers container for event listener functions + */ +const setFsWatchListener = (path, fullPath, options, handlers) => { + const {listener, errHandler, rawEmitter} = handlers; + let cont = FsWatchInstances.get(fullPath); + + /** @type {fs.FSWatcher=} */ + let watcher; + if (!options.persistent) { + watcher = createFsWatchInstance( + path, options, listener, errHandler, rawEmitter + ); + return watcher.close.bind(watcher); + } + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_ERR, errHandler); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + watcher = createFsWatchInstance( + path, + options, + fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), + errHandler, // no need to use broadcast here + fsWatchBroadcast.bind(null, fullPath, KEY_RAW) + ); + if (!watcher) return; + watcher.on(EV_ERROR, async (error) => { + const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); + cont.watcherUnusable = true; // documented since Node 10.4.1 + // Workaround for https://github.com/joyent/node/issues/4337 + if (isWindows && error.code === 'EPERM') { + try { + const fd = await open(path, 'r'); + await close(fd); + broadcastErr(error); + } catch (err) {} + } else { + broadcastErr(error); + } + }); + cont = { + listeners: listener, + errHandlers: errHandler, + rawEmitters: rawEmitter, + watcher + }; + FsWatchInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // removes this instance's listeners and closes the underlying fs_watch + // instance if there are no more listeners left + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_ERR, errHandler); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + // Check to protect against issue gh-730. + // if (cont.watcherUnusable) { + cont.watcher.close(); + // } + FsWatchInstances.delete(fullPath); + HANDLER_KEYS.forEach(clearItem(cont)); + cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +// fs_watchFile helpers + +// object to hold per-process fs_watchFile instances +// (may be shared across chokidar FSWatcher instances) +const FsWatchFileInstances = new Map(); + +/** + * Instantiates the fs_watchFile interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path to be watched + * @param {String} fullPath absolute path + * @param {Object} options options to be passed to fs_watchFile + * @param {Object} handlers container for event listener functions + * @returns {Function} closer + */ +const setFsWatchFileListener = (path, fullPath, options, handlers) => { + const {listener, rawEmitter} = handlers; + let cont = FsWatchFileInstances.get(fullPath); + + /* eslint-disable no-unused-vars, prefer-destructuring */ + let listeners = new Set(); + let rawEmitters = new Set(); + + const copts = cont && cont.options; + if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { + // "Upgrade" the watcher to persistence or a quicker interval. + // This creates some unlikely edge case issues if the user mixes + // settings in a very weird way, but solving for those cases + // doesn't seem worthwhile for the added complexity. + listeners = cont.listeners; + rawEmitters = cont.rawEmitters; + fs.unwatchFile(fullPath); + cont = undefined; + } + + /* eslint-enable no-unused-vars, prefer-destructuring */ + + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + // TODO + // listeners.add(listener); + // rawEmitters.add(rawEmitter); + cont = { + listeners: listener, + rawEmitters: rawEmitter, + options, + watcher: fs.watchFile(fullPath, options, (curr, prev) => { + foreach(cont.rawEmitters, (rawEmitter) => { + rawEmitter(EV_CHANGE, fullPath, {curr, prev}); + }); + const currmtime = curr.mtimeMs; + if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { + foreach(cont.listeners, (listener) => listener(path, curr)); + } + }) + }; + FsWatchFileInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // Removes this instance's listeners and closes the underlying fs_watchFile + // instance if there are no more listeners left. + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + FsWatchFileInstances.delete(fullPath); + fs.unwatchFile(fullPath); + cont.options = cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +/** + * @mixin + */ +class NodeFsHandler { + +/** + * @param {import("../index").FSWatcher} fsW + */ +constructor(fsW) { + this.fsw = fsW; + this._boundHandleError = (error) => fsW._handleError(error); +} + +/** + * Watch file for changes with fs_watchFile or fs_watch. + * @param {String} path to file or dir + * @param {Function} listener on fs change + * @returns {Function} closer for the watcher instance + */ +_watchWithNodeFs(path, listener) { + const opts = this.fsw.options; + const directory = sysPath.dirname(path); + const basename = sysPath.basename(path); + const parent = this.fsw._getWatchedDir(directory); + parent.add(basename); + const absolutePath = sysPath.resolve(path); + const options = {persistent: opts.persistent}; + if (!listener) listener = EMPTY_FN; + + let closer; + if (opts.usePolling) { + options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? + opts.binaryInterval : opts.interval; + closer = setFsWatchFileListener(path, absolutePath, options, { + listener, + rawEmitter: this.fsw._emitRaw + }); + } else { + closer = setFsWatchListener(path, absolutePath, options, { + listener, + errHandler: this._boundHandleError, + rawEmitter: this.fsw._emitRaw + }); + } + return closer; +} + +/** + * Watch a file and emit add event if warranted. + * @param {Path} file Path + * @param {fs.Stats} stats result of fs_stat + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @returns {Function} closer for the watcher instance + */ +_handleFile(file, stats, initialAdd) { + if (this.fsw.closed) { + return; + } + const dirname = sysPath.dirname(file); + const basename = sysPath.basename(file); + const parent = this.fsw._getWatchedDir(dirname); + // stats is always present + let prevStats = stats; + + // if the file is already being watched, do nothing + if (parent.has(basename)) return; + + const listener = async (path, newStats) => { + if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return; + if (!newStats || newStats.mtimeMs === 0) { + try { + const newStats = await stat(file); + if (this.fsw.closed) return; + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats); + } + if (isLinux && prevStats.ino !== newStats.ino) { + this.fsw._closeFile(path) + prevStats = newStats; + this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener)); + } else { + prevStats = newStats; + } + } catch (error) { + // Fix issues where mtime is null but file is still present + this.fsw._remove(dirname, basename); + } + // add is about to be emitted if file not already tracked in parent + } else if (parent.has(basename)) { + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats); + } + prevStats = newStats; + } + } + // kick off the watcher + const closer = this._watchWithNodeFs(file, listener); + + // emit an add event if we're supposed to + if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) { + if (!this.fsw._throttle(EV_ADD, file, 0)) return; + this.fsw._emit(EV_ADD, file, stats); + } + + return closer; +} + +/** + * Handle symlinks encountered while reading a dir. + * @param {Object} entry returned by readdirp + * @param {String} directory path of dir being read + * @param {String} path of this item + * @param {String} item basename of this item + * @returns {Promise} true if no more processing is needed for this entry. + */ +async _handleSymlink(entry, directory, path, item) { + if (this.fsw.closed) { + return; + } + const full = entry.fullPath; + const dir = this.fsw._getWatchedDir(directory); + + if (!this.fsw.options.followSymlinks) { + // watch symlink directly (don't follow) and detect changes + this.fsw._incrReadyCount(); + + let linkPath; + try { + linkPath = await fsrealpath(path); + } catch (e) { + this.fsw._emitReady(); + return true; + } + + if (this.fsw.closed) return; + if (dir.has(item)) { + if (this.fsw._symlinkPaths.get(full) !== linkPath) { + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_CHANGE, path, entry.stats); + } + } else { + dir.add(item); + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_ADD, path, entry.stats); + } + this.fsw._emitReady(); + return true; + } + + // don't follow the same symlink more than once + if (this.fsw._symlinkPaths.has(full)) { + return true; + } + + this.fsw._symlinkPaths.set(full, true); +} + +_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { + // Normalize the directory name on Windows + directory = sysPath.join(directory, EMPTY_STR); + + if (!wh.hasGlob) { + throttler = this.fsw._throttle('readdir', directory, 1000); + if (!throttler) return; + } + + const previous = this.fsw._getWatchedDir(wh.path); + const current = new Set(); + + let stream = this.fsw._readdirp(directory, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + depth: 0 + }).on(STR_DATA, async (entry) => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const item = entry.path; + let path = sysPath.join(directory, item); + current.add(item); + + if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) { + return; + } + + if (this.fsw.closed) { + stream = undefined; + return; + } + // Files that present in current directory snapshot + // but absent in previous are added to watch list and + // emit `add` event. + if (item === target || !target && !previous.has(item)) { + this.fsw._incrReadyCount(); + + // ensure relativeness of path is preserved in case of watcher reuse + path = sysPath.join(dir, sysPath.relative(dir, path)); + + this._addToNodeFs(path, initialAdd, wh, depth + 1); + } + }).on(EV_ERROR, this._boundHandleError); + + return new Promise(resolve => + stream.once(STR_END, () => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const wasThrottled = throttler ? throttler.clear() : false; + + resolve(); + + // Files that absent in current directory snapshot + // but present in previous emit `remove` event + // and are removed from @watched[directory]. + previous.getChildren().filter((item) => { + return item !== directory && + !current.has(item) && + // in case of intersecting globs; + // a path may have been filtered out of this readdir, but + // shouldn't be removed because it matches a different glob + (!wh.hasGlob || wh.filterPath({ + fullPath: sysPath.resolve(directory, item) + })); + }).forEach((item) => { + this.fsw._remove(directory, item); + }); + + stream = undefined; + + // one more time for any missed in case changes came in extremely quickly + if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler); + }) + ); +} + +/** + * Read directory to add / remove files from `@watched` list and re-read it on change. + * @param {String} dir fs path + * @param {fs.Stats} stats + * @param {Boolean} initialAdd + * @param {Number} depth relative to user-supplied path + * @param {String} target child path targeted for watch + * @param {Object} wh Common watch helpers for this path + * @param {String} realpath + * @returns {Promise} closer for the watcher instance. + */ +async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) { + const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir)); + const tracked = parentDir.has(sysPath.basename(dir)); + if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { + if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats); + } + + // ensure dir is tracked (harmless if redundant) + parentDir.add(sysPath.basename(dir)); + this.fsw._getWatchedDir(dir); + let throttler; + let closer; + + const oDepth = this.fsw.options.depth; + if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) { + if (!target) { + await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); + if (this.fsw.closed) return; + } + + closer = this._watchWithNodeFs(dir, (dirPath, stats) => { + // if current directory is removed, do nothing + if (stats && stats.mtimeMs === 0) return; + + this._handleRead(dirPath, false, wh, target, dir, depth, throttler); + }); + } + return closer; +} + +/** + * Handle added file, directory, or glob pattern. + * Delegates call to _handleFile / _handleDir after checks. + * @param {String} path to file or ir + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @param {Object} priorWh depth relative to user-supplied path + * @param {Number} depth Child path actually targeted for watch + * @param {String=} target Child path actually targeted for watch + * @returns {Promise} + */ +async _addToNodeFs(path, initialAdd, priorWh, depth, target) { + const ready = this.fsw._emitReady; + if (this.fsw._isIgnored(path) || this.fsw.closed) { + ready(); + return false; + } + + const wh = this.fsw._getWatchHelpers(path, depth); + if (!wh.hasGlob && priorWh) { + wh.hasGlob = priorWh.hasGlob; + wh.globFilter = priorWh.globFilter; + wh.filterPath = entry => priorWh.filterPath(entry); + wh.filterDir = entry => priorWh.filterDir(entry); + } + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + ready(); + return false; + } + + const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START); + let closer; + if (stats.isDirectory()) { + const absPath = sysPath.resolve(path); + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); + if (this.fsw.closed) return; + // preserve this symlink's target path + if (absPath !== targetPath && targetPath !== undefined) { + this.fsw._symlinkPaths.set(absPath, targetPath); + } + } else if (stats.isSymbolicLink()) { + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + const parent = sysPath.dirname(wh.watchPath); + this.fsw._getWatchedDir(parent).add(wh.watchPath); + this.fsw._emit(EV_ADD, wh.watchPath, stats); + closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath); + if (this.fsw.closed) return; + + // preserve this symlink's target path + if (targetPath !== undefined) { + this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath); + } + } else { + closer = this._handleFile(wh.watchPath, stats, initialAdd); + } + ready(); + + this.fsw._addPathCloser(path, closer); + return false; + + } catch (error) { + if (this.fsw._handleError(error)) { + ready(); + return path; + } + } +} + +} + +module.exports = NodeFsHandler; diff --git a/node_modules/chokidar/package.json b/node_modules/chokidar/package.json new file mode 100644 index 0000000..e8f8b3d --- /dev/null +++ b/node_modules/chokidar/package.json @@ -0,0 +1,70 @@ +{ + "name": "chokidar", + "description": "Minimal and efficient cross-platform file watching library", + "version": "3.6.0", + "homepage": "https://github.com/paulmillr/chokidar", + "author": "Paul Miller (https://paulmillr.com)", + "contributors": [ + "Paul Miller (https://paulmillr.com)", + "Elan Shanker" + ], + "engines": { + "node": ">= 8.10.0" + }, + "main": "index.js", + "types": "./types/index.d.ts", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "devDependencies": { + "@types/node": "^14", + "chai": "^4.3", + "dtslint": "^3.3.0", + "eslint": "^7.0.0", + "mocha": "^7.0.0", + "rimraf": "^3.0.0", + "sinon": "^9.0.1", + "sinon-chai": "^3.3.0", + "typescript": "^4.4.3", + "upath": "^1.2.0" + }, + "files": [ + "index.js", + "lib/*.js", + "types/index.d.ts" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/chokidar.git" + }, + "bugs": { + "url": "https://github.com/paulmillr/chokidar/issues" + }, + "license": "MIT", + "scripts": { + "dtslint": "dtslint types", + "lint": "eslint --report-unused-disable-directives --ignore-path .gitignore .", + "build": "npm ls", + "mocha": "mocha --exit --timeout 90000", + "test": "npm run lint && npm run mocha" + }, + "keywords": [ + "fs", + "watch", + "watchFile", + "watcher", + "watching", + "file", + "fsevents" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/node_modules/chokidar/types/index.d.ts b/node_modules/chokidar/types/index.d.ts new file mode 100644 index 0000000..4558066 --- /dev/null +++ b/node_modules/chokidar/types/index.d.ts @@ -0,0 +1,192 @@ +// TypeScript Version: 3.0 + +/// + +import * as fs from "fs"; +import { EventEmitter } from "events"; +import { Matcher } from 'anymatch'; + +export class FSWatcher extends EventEmitter implements fs.FSWatcher { + options: WatchOptions; + + /** + * Constructs a new FSWatcher instance with optional WatchOptions parameter. + */ + constructor(options?: WatchOptions); + + /** + * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one + * string. + */ + add(paths: string | ReadonlyArray): this; + + /** + * Stop watching files, directories, or glob patterns. Takes an array of strings or just one + * string. + */ + unwatch(paths: string | ReadonlyArray): this; + + /** + * Returns an object representing all the paths on the file system being watched by this + * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless + * the `cwd` option was used), and the values are arrays of the names of the items contained in + * each directory. + */ + getWatched(): { + [directory: string]: string[]; + }; + + /** + * Removes all listeners from watched files. + */ + close(): Promise; + + on(event: 'add'|'addDir'|'change', listener: (path: string, stats?: fs.Stats) => void): this; + + on(event: 'all', listener: (eventName: 'add'|'addDir'|'change'|'unlink'|'unlinkDir', path: string, stats?: fs.Stats) => void): this; + + /** + * Error occurred + */ + on(event: 'error', listener: (error: Error) => void): this; + + /** + * Exposes the native Node `fs.FSWatcher events` + */ + on(event: 'raw', listener: (eventName: string, path: string, details: any) => void): this; + + /** + * Fires when the initial scan is complete + */ + on(event: 'ready', listener: () => void): this; + + on(event: 'unlink'|'unlinkDir', listener: (path: string) => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + + ref(): this; + + unref(): this; +} + +export interface WatchOptions { + /** + * Indicates whether the process should continue to run as long as files are being watched. If + * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`, + * even if the process continues to run. + */ + persistent?: boolean; + + /** + * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to + * be ignored. The whole relative or absolute path is tested, not just filename. If a function + * with two arguments is provided, it gets called twice per path - once with a single argument + * (the path), second time with two arguments (the path and the + * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path). + */ + ignored?: Matcher; + + /** + * If set to `false` then `add`/`addDir` events are also emitted for matching paths while + * instantiating the watching as chokidar discovers these file paths (before the `ready` event). + */ + ignoreInitial?: boolean; + + /** + * When `false`, only the symlinks themselves will be watched for changes instead of following + * the link references and bubbling events through the link's path. + */ + followSymlinks?: boolean; + + /** + * The base directory from which watch `paths` are to be derived. Paths emitted with events will + * be relative to this. + */ + cwd?: string; + + /** + * If set to true then the strings passed to .watch() and .add() are treated as literal path + * names, even if they look like globs. Default: false. + */ + disableGlobbing?: boolean; + + /** + * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU + * utilization, consider setting this to `false`. It is typically necessary to **set this to + * `true` to successfully watch files over a network**, and it may be necessary to successfully + * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides + * the `useFsEvents` default. + */ + usePolling?: boolean; + + /** + * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly + * and `fsevents` is available this supercedes the `usePolling` setting. When set to `false` on + * OS X, `usePolling: true` becomes the default. + */ + useFsEvents?: boolean; + + /** + * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that + * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is + * provided even in cases where it wasn't already available from the underlying watch events. + */ + alwaysStat?: boolean; + + /** + * If set, limits how many levels of subdirectories will be traversed. + */ + depth?: number; + + /** + * Interval of file system polling. + */ + interval?: number; + + /** + * Interval of file system polling for binary files. ([see list of binary extensions](https://gi + * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) + */ + binaryInterval?: number; + + /** + * Indicates whether to watch files that don't have read permissions if possible. If watching + * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed + * silently. + */ + ignorePermissionErrors?: boolean; + + /** + * `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts + * that occur when using editors that use "atomic writes" instead of writing directly to the + * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change` + * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you, + * you can override it by setting `atomic` to a custom value, in milliseconds. + */ + atomic?: boolean | number; + + /** + * can be set to an object in order to adjust timing params: + */ + awaitWriteFinish?: AwaitWriteFinishOptions | boolean; +} + +export interface AwaitWriteFinishOptions { + /** + * Amount of time in milliseconds for a file size to remain constant before emitting its event. + */ + stabilityThreshold?: number; + + /** + * File size polling interval. + */ + pollInterval?: number; +} + +/** + * produces an instance of `FSWatcher`. + */ +export function watch( + paths: string | ReadonlyArray, + options?: WatchOptions +): FSWatcher; diff --git a/node_modules/concat-map/.travis.yml b/node_modules/concat-map/.travis.yml new file mode 100644 index 0000000..f1d0f13 --- /dev/null +++ b/node_modules/concat-map/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.4 + - 0.6 diff --git a/node_modules/concat-map/LICENSE b/node_modules/concat-map/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/concat-map/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/concat-map/README.markdown b/node_modules/concat-map/README.markdown new file mode 100644 index 0000000..408f70a --- /dev/null +++ b/node_modules/concat-map/README.markdown @@ -0,0 +1,62 @@ +concat-map +========== + +Concatenative mapdashery. + +[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map) + +[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map) + +example +======= + +``` js +var concatMap = require('concat-map'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); +``` + +*** + +``` +[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ] +``` + +methods +======= + +``` js +var concatMap = require('concat-map') +``` + +concatMap(xs, fn) +----------------- + +Return an array of concatenated elements by calling `fn(x, i)` for each element +`x` and each index `i` in the array `xs`. + +When `fn(x, i)` returns an array, its result will be concatenated with the +result array. If `fn(x, i)` returns anything else, that value will be pushed +onto the end of the result array. + +install +======= + +With [npm](http://npmjs.org) do: + +``` +npm install concat-map +``` + +license +======= + +MIT + +notes +===== + +This module was written while sitting high above the ground in a tree. diff --git a/node_modules/concat-map/example/map.js b/node_modules/concat-map/example/map.js new file mode 100644 index 0000000..3365621 --- /dev/null +++ b/node_modules/concat-map/example/map.js @@ -0,0 +1,6 @@ +var concatMap = require('../'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); diff --git a/node_modules/concat-map/index.js b/node_modules/concat-map/index.js new file mode 100644 index 0000000..b29a781 --- /dev/null +++ b/node_modules/concat-map/index.js @@ -0,0 +1,13 @@ +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; diff --git a/node_modules/concat-map/package.json b/node_modules/concat-map/package.json new file mode 100644 index 0000000..d3640e6 --- /dev/null +++ b/node_modules/concat-map/package.json @@ -0,0 +1,43 @@ +{ + "name" : "concat-map", + "description" : "concatenative mapdashery", + "version" : "0.0.1", + "repository" : { + "type" : "git", + "url" : "git://github.com/substack/node-concat-map.git" + }, + "main" : "index.js", + "keywords" : [ + "concat", + "concatMap", + "map", + "functional", + "higher-order" + ], + "directories" : { + "example" : "example", + "test" : "test" + }, + "scripts" : { + "test" : "tape test/*.js" + }, + "devDependencies" : { + "tape" : "~2.4.0" + }, + "license" : "MIT", + "author" : { + "name" : "James Halliday", + "email" : "mail@substack.net", + "url" : "http://substack.net" + }, + "testling" : { + "files" : "test/*.js", + "browsers" : { + "ie" : [ 6, 7, 8, 9 ], + "ff" : [ 3.5, 10, 15.0 ], + "chrome" : [ 10, 22 ], + "safari" : [ 5.1 ], + "opera" : [ 12 ] + } + } +} diff --git a/node_modules/concat-map/test/map.js b/node_modules/concat-map/test/map.js new file mode 100644 index 0000000..fdbd702 --- /dev/null +++ b/node_modules/concat-map/test/map.js @@ -0,0 +1,39 @@ +var concatMap = require('../'); +var test = require('tape'); + +test('empty or not', function (t) { + var xs = [ 1, 2, 3, 4, 5, 6 ]; + var ixes = []; + var ys = concatMap(xs, function (x, ix) { + ixes.push(ix); + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; + }); + t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]); + t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]); + t.end(); +}); + +test('always something', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ]; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('scalars', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : x; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('undefs', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function () {}); + t.same(ys, [ undefined, undefined, undefined, undefined ]); + t.end(); +}); diff --git a/node_modules/content-disposition/HISTORY.md b/node_modules/content-disposition/HISTORY.md new file mode 100644 index 0000000..488effa --- /dev/null +++ b/node_modules/content-disposition/HISTORY.md @@ -0,0 +1,60 @@ +0.5.4 / 2021-12-10 +================== + + * deps: safe-buffer@5.2.1 + +0.5.3 / 2018-12-17 +================== + + * Use `safe-buffer` for improved Buffer API + +0.5.2 / 2016-12-08 +================== + + * Fix `parse` to accept any linear whitespace character + +0.5.1 / 2016-01-17 +================== + + * perf: enable strict mode + +0.5.0 / 2014-10-11 +================== + + * Add `parse` function + +0.4.0 / 2014-09-21 +================== + + * Expand non-Unicode `filename` to the full ISO-8859-1 charset + +0.3.0 / 2014-09-20 +================== + + * Add `fallback` option + * Add `type` option + +0.2.0 / 2014-09-19 +================== + + * Reduce ambiguity of file names with hex escape in buggy browsers + +0.1.2 / 2014-09-19 +================== + + * Fix periodic invalid Unicode filename header + +0.1.1 / 2014-09-19 +================== + + * Fix invalid characters appearing in `filename*` parameter + +0.1.0 / 2014-09-18 +================== + + * Make the `filename` argument optional + +0.0.0 / 2014-09-18 +================== + + * Initial release diff --git a/node_modules/content-disposition/LICENSE b/node_modules/content-disposition/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/node_modules/content-disposition/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/content-disposition/README.md b/node_modules/content-disposition/README.md new file mode 100644 index 0000000..3a0bb05 --- /dev/null +++ b/node_modules/content-disposition/README.md @@ -0,0 +1,142 @@ +# content-disposition + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create and parse HTTP `Content-Disposition` header + +## Installation + +```sh +$ npm install content-disposition +``` + +## API + +```js +var contentDisposition = require('content-disposition') +``` + +### contentDisposition(filename, options) + +Create an attachment `Content-Disposition` header value using the given file name, +if supplied. The `filename` is optional and if no file name is desired, but you +want to specify `options`, set `filename` to `undefined`. + +```js +res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) +``` + +**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this +header through a means different from `setHeader` in Node.js, you'll want to specify +the `'binary'` encoding in Node.js. + +#### Options + +`contentDisposition` accepts these properties in the options object. + +##### fallback + +If the `filename` option is outside ISO-8859-1, then the file name is actually +stored in a supplemental field for clients that support Unicode file names and +a ISO-8859-1 version of the file name is automatically generated. + +This specifies the ISO-8859-1 file name to override the automatic generation or +disables the generation all together, defaults to `true`. + + - A string will specify the ISO-8859-1 file name to use in place of automatic + generation. + - `false` will disable including a ISO-8859-1 file name and only include the + Unicode version (unless the file name is already ISO-8859-1). + - `true` will enable automatic generation if the file name is outside ISO-8859-1. + +If the `filename` option is ISO-8859-1 and this option is specified and has a +different value, then the `filename` option is encoded in the extended field +and this set as the fallback field, even though they are both ISO-8859-1. + +##### type + +Specifies the disposition type, defaults to `"attachment"`. This can also be +`"inline"`, or any other value (all values except inline are treated like +`attachment`, but can convey additional information if both parties agree to +it). The type is normalized to lower-case. + +### contentDisposition.parse(string) + +```js +var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt') +``` + +Parse a `Content-Disposition` header string. This automatically handles extended +("Unicode") parameters by decoding them and providing them under the standard +parameter name. This will return an object with the following properties (examples +are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): + + - `type`: The disposition type (always lower case). Example: `'attachment'` + + - `parameters`: An object of the parameters in the disposition (name of parameter + always lower case and extended versions replace non-extended versions). Example: + `{filename: "€ rates.txt"}` + +## Examples + +### Send a file for download + +```js +var contentDisposition = require('content-disposition') +var destroy = require('destroy') +var fs = require('fs') +var http = require('http') +var onFinished = require('on-finished') + +var filePath = '/path/to/public/plans.pdf' + +http.createServer(function onRequest (req, res) { + // set headers + res.setHeader('Content-Type', 'application/pdf') + res.setHeader('Content-Disposition', contentDisposition(filePath)) + + // send file + var stream = fs.createReadStream(filePath) + stream.pipe(res) + onFinished(res, function () { + destroy(stream) + }) +}) +``` + +## Testing + +```sh +$ npm test +``` + +## References + +- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] +- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] +- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] +- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] + +[rfc-2616]: https://tools.ietf.org/html/rfc2616 +[rfc-5987]: https://tools.ietf.org/html/rfc5987 +[rfc-6266]: https://tools.ietf.org/html/rfc6266 +[tc-2231]: http://greenbytes.de/tech/tc2231/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-disposition.svg +[npm-url]: https://npmjs.org/package/content-disposition +[node-version-image]: https://img.shields.io/node/v/content-disposition.svg +[node-version-url]: https://nodejs.org/en/download +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master +[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg +[downloads-url]: https://npmjs.org/package/content-disposition +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/jshttp/content-disposition/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/content-disposition?query=workflow%3Aci diff --git a/node_modules/content-disposition/index.js b/node_modules/content-disposition/index.js new file mode 100644 index 0000000..ecec899 --- /dev/null +++ b/node_modules/content-disposition/index.js @@ -0,0 +1,458 @@ +/*! + * content-disposition + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = contentDisposition +module.exports.parse = parse + +/** + * Module dependencies. + * @private + */ + +var basename = require('path').basename +var Buffer = require('safe-buffer').Buffer + +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + * @private + */ + +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex + +/** + * RegExp to match percent encoding escape. + * @private + */ + +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g + +/** + * RegExp to match non-latin1 characters. + * @private + */ + +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + * @private + */ + +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex + +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @private + */ + +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp for various RFC 2616 grammar + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = + * @private + */ + +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ + +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + * @private + */ + +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ + +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + * @private + */ + +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex + +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @public + */ + +function contentDisposition (filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @private + */ + +function createparams (filename, fallback) { + if (filename === undefined) { + return + } + + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } + + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } + + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } + + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } + + // restrict to file base name + var name = basename(filename) + + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) + + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name + } + + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } + + return params +} + +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private + */ + +function format (obj) { + var parameters = obj.parameters + var type = obj.type + + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + // start with normalized type + var string = String(type).toLowerCase() + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val + } + } + + return string +} + +/** + * Decode a RFC 5987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @private + */ + +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) + + if (!match) { + throw new TypeError('invalid extended field value') + } + + var charset = match[1].toLowerCase() + var encoded = match[2] + var value + + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) + + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = Buffer.from(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } + + return value +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @private + */ + +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @public + */ + +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + + var match = DISPOSITION_TYPE_REGEXP.exec(string) + + if (!match) { + throw new TypeError('invalid type format') + } + + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index + + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + + params[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @private + */ + +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @private + */ + +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @private + */ + +function ustring (val) { + var str = String(val) + + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + + return 'UTF-8\'\'' + encoded +} + +/** + * Class for parsed Content-Disposition header for v8 optimization + * + * @public + * @param {string} type + * @param {object} parameters + * @constructor + */ + +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} diff --git a/node_modules/content-disposition/package.json b/node_modules/content-disposition/package.json new file mode 100644 index 0000000..43c70ce --- /dev/null +++ b/node_modules/content-disposition/package.json @@ -0,0 +1,44 @@ +{ + "name": "content-disposition", + "description": "Create and parse Content-Disposition header", + "version": "0.5.4", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "content-disposition", + "http", + "rfc6266", + "res" + ], + "repository": "jshttp/content-disposition", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "7.32.0", + "eslint-config-standard": "13.0.1", + "eslint-plugin-import": "2.25.3", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "istanbul": "0.4.5", + "mocha": "9.1.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + } +} diff --git a/node_modules/content-type/HISTORY.md b/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..4583671 --- /dev/null +++ b/node_modules/content-type/HISTORY.md @@ -0,0 +1,29 @@ +1.0.5 / 2023-01-29 +================== + + * perf: skip value escaping when unnecessary + +1.0.4 / 2017-09-11 +================== + + * perf: skip parameter parsing when no parameters + +1.0.3 / 2017-09-10 +================== + + * perf: remove argument reassignment + +1.0.2 / 2016-05-09 +================== + + * perf: enable strict mode + +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/node_modules/content-type/LICENSE b/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/content-type/README.md b/node_modules/content-type/README.md new file mode 100644 index 0000000..c1a922a --- /dev/null +++ b/node_modules/content-type/README.md @@ -0,0 +1,94 @@ +# content-type + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a `Content-Type` header. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `Content-Type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `Content-Type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({ + type: 'image/svg+xml', + parameters: { charset: 'utf-8' } +}) +``` + +Format an object into a `Content-Type` header. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/content-type/master?label=ci +[ci-url]: https://github.com/jshttp/content-type/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/content-type/master +[coveralls-url]: https://coveralls.io/r/jshttp/content-type?branch=master +[node-image]: https://badgen.net/npm/node/content-type +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/content-type +[npm-url]: https://npmjs.org/package/content-type +[npm-version-image]: https://badgen.net/npm/v/content-type diff --git a/node_modules/content-type/index.js b/node_modules/content-type/index.js new file mode 100644 index 0000000..41840e7 --- /dev/null +++ b/node_modules/content-type/index.js @@ -0,0 +1,225 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ // eslint-disable-line no-control-regex +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g // eslint-disable-line no-control-regex + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } + + string += '; ' + param + '=' + qstring(parameters[param]) + } + } + + return string +} + +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string + + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = header.indexOf(';') + var type = index !== -1 + ? header.slice(0, index).trim() + : header.trim() + + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } + + var obj = new ContentType(type.toLowerCase()) + + // parse parameters + if (index !== -1) { + var key + var match + var value + + PARAM_REGEXP.lastIndex = index + + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (value.charCodeAt(0) === 0x22 /* " */) { + // remove quotes + value = value.slice(1, -1) + + // remove escapes + if (value.indexOf('\\') !== -1) { + value = value.replace(QESC_REGEXP, '$1') + } + } + + obj.parameters[key] = value + } + + if (index !== header.length) { + throw new TypeError('invalid parameter format') + } + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + +function getcontenttype (obj) { + var header + + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] + } + + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } + + return header +} + +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } + + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') + } + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/node_modules/content-type/package.json b/node_modules/content-type/package.json new file mode 100644 index 0000000..9db19f6 --- /dev/null +++ b/node_modules/content-type/package.json @@ -0,0 +1,42 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.5", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": "jshttp/content-type", + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "8.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "10.2.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/cookie-signature/.npmignore b/node_modules/cookie-signature/.npmignore new file mode 100644 index 0000000..f1250e5 --- /dev/null +++ b/node_modules/cookie-signature/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/node_modules/cookie-signature/History.md b/node_modules/cookie-signature/History.md new file mode 100644 index 0000000..78513cc --- /dev/null +++ b/node_modules/cookie-signature/History.md @@ -0,0 +1,38 @@ +1.0.6 / 2015-02-03 +================== + +* use `npm test` instead of `make test` to run tests +* clearer assertion messages when checking input + + +1.0.5 / 2014-09-05 +================== + +* add license to package.json + +1.0.4 / 2014-06-25 +================== + + * corrected avoidance of timing attacks (thanks @tenbits!) + +1.0.3 / 2014-01-28 +================== + + * [incorrect] fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/cookie-signature/Readme.md b/node_modules/cookie-signature/Readme.md new file mode 100644 index 0000000..2559e84 --- /dev/null +++ b/node_modules/cookie-signature/Readme.md @@ -0,0 +1,42 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +(The MIT License) + +Copyright (c) 2012 LearnBoost <tj@learnboost.com> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/cookie-signature/index.js b/node_modules/cookie-signature/index.js new file mode 100644 index 0000000..b8c9463 --- /dev/null +++ b/node_modules/cookie-signature/index.js @@ -0,0 +1,51 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return sha1(mac) == sha1(val) ? str : false; +}; + +/** + * Private + */ + +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} diff --git a/node_modules/cookie-signature/package.json b/node_modules/cookie-signature/package.json new file mode 100644 index 0000000..29c4498 --- /dev/null +++ b/node_modules/cookie-signature/package.json @@ -0,0 +1,18 @@ +{ + "name": "cookie-signature", + "version": "1.0.6", + "description": "Sign and unsign cookies", + "keywords": ["cookie", "sign", "unsign"], + "author": "TJ Holowaychuk ", + "license": "MIT", + "repository": { "type": "git", "url": "https://github.com/visionmedia/node-cookie-signature.git"}, + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + }, + "main": "index" +} diff --git a/node_modules/cookie/LICENSE b/node_modules/cookie/LICENSE new file mode 100644 index 0000000..058b6b4 --- /dev/null +++ b/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/cookie/README.md b/node_modules/cookie/README.md new file mode 100644 index 0000000..71fdac1 --- /dev/null +++ b/node_modules/cookie/README.md @@ -0,0 +1,317 @@ +# cookie + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Basic HTTP cookie parser and serializer for HTTP servers. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install cookie +``` + +## API + +```js +var cookie = require('cookie'); +``` + +### cookie.parse(str, options) + +Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs. +The `str` argument is the string representing a `Cookie` header value and `options` is an +optional object containing additional parsing options. + +```js +var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); +// { foo: 'bar', equation: 'E=mc^2' } +``` + +#### Options + +`cookie.parse` accepts these properties in the options object. + +##### decode + +Specifies a function that will be used to decode a cookie's value. Since the value of a cookie +has a limited character set (and must be a simple string), this function can be used to decode +a previously-encoded cookie value into a JavaScript string or other object. + +The default function is the global `decodeURIComponent`, which will decode any URL-encoded +sequences into their byte representations. + +**note** if an error is thrown from this function, the original, non-decoded cookie value will +be returned as the cookie's value. + +### cookie.serialize(name, value, options) + +Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the +name for the cookie, the `value` argument is the value to set the cookie to, and the `options` +argument is an optional object containing additional serialization options. + +```js +var setCookie = cookie.serialize('foo', 'bar'); +// foo=bar +``` + +#### Options + +`cookie.serialize` accepts these properties in the options object. + +##### domain + +Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no +domain is set, and most clients will consider the cookie to apply to only the current domain. + +##### encode + +Specifies a function that will be used to encode a cookie's value. Since value of a cookie +has a limited character set (and must be a simple string), this function can be used to encode +a value into a string suited for a cookie's value. + +The default function is the global `encodeURIComponent`, which will encode a JavaScript string +into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range. + +##### expires + +Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1]. +By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and +will delete it on a condition like exiting a web browser application. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### httpOnly + +Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy, +the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not allow client-side +JavaScript to see the cookie in `document.cookie`. + +##### maxAge + +Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2]. +The given number will be converted to an integer by rounding down. By default, no maximum age is set. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### partitioned + +Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](rfc-cutler-httpbis-partitioned-cookies) +attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the +`Partitioned` attribute is not set. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +More information about can be found in [the proposal](https://github.com/privacycg/CHIPS). + +##### path + +Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path +is considered the ["default path"][rfc-6265-5.1.4]. + +##### priority + +Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1]. + + - `'low'` will set the `Priority` attribute to `Low`. + - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. + - `'high'` will set the `Priority` attribute to `High`. + +More information about the different priority levels can be found in +[the specification][rfc-west-cookie-priority-00-4.1]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### sameSite + +Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-09-5.4.7]. + + - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + - `false` will not set the `SameSite` attribute. + - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. + - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. + - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + +More information about the different enforcement levels can be found in +[the specification][rfc-6265bis-09-5.4.7]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### secure + +Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy, +the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to +the server in the future if the browser does not have an HTTPS connection. + +## Example + +The following example uses this module in conjunction with the Node.js core HTTP server +to prompt a user for their name and display it back on future visits. + +```js +var cookie = require('cookie'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var url = require('url'); + +function onRequest(req, res) { + // Parse the query string + var query = url.parse(req.url, true, true).query; + + if (query && query.name) { + // Set a new cookie with the name + res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), { + httpOnly: true, + maxAge: 60 * 60 * 24 * 7 // 1 week + })); + + // Redirect back after setting cookie + res.statusCode = 302; + res.setHeader('Location', req.headers.referer || '/'); + res.end(); + return; + } + + // Parse the cookies on the request + var cookies = cookie.parse(req.headers.cookie || ''); + + // Get the visitor name set in the cookie + var name = cookies.name; + + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + + if (name) { + res.write('

Welcome back, ' + escapeHtml(name) + '!

'); + } else { + res.write('

Hello, new visitor!

'); + } + + res.write('
'); + res.write(' '); + res.end('
'); +} + +http.createServer(onRequest).listen(3000); +``` + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +``` +$ npm run bench + +> cookie@0.5.0 bench +> node benchmark/index.js + + node@18.18.2 + acorn@8.10.0 + ada@2.6.0 + ares@1.19.1 + brotli@1.0.9 + cldr@43.1 + icu@73.2 + llhttp@6.0.11 + modules@108 + napi@9 + nghttp2@1.57.0 + nghttp3@0.7.0 + ngtcp2@0.8.1 + openssl@3.0.10+quic + simdutf@3.2.14 + tz@2023c + undici@5.26.3 + unicode@15.0 + uv@1.44.2 + uvwasi@0.0.18 + v8@10.2.154.26-node.26 + zlib@1.2.13.1-motley + +> node benchmark/parse-top.js + + cookie.parse - top sites + + 14 tests completed. + + parse accounts.google.com x 2,588,913 ops/sec ±0.74% (186 runs sampled) + parse apple.com x 2,370,002 ops/sec ±0.69% (186 runs sampled) + parse cloudflare.com x 2,213,102 ops/sec ±0.88% (188 runs sampled) + parse docs.google.com x 2,194,157 ops/sec ±1.03% (184 runs sampled) + parse drive.google.com x 2,265,084 ops/sec ±0.79% (187 runs sampled) + parse en.wikipedia.org x 457,099 ops/sec ±0.81% (186 runs sampled) + parse linkedin.com x 504,407 ops/sec ±0.89% (186 runs sampled) + parse maps.google.com x 1,230,959 ops/sec ±0.98% (186 runs sampled) + parse microsoft.com x 926,294 ops/sec ±0.88% (184 runs sampled) + parse play.google.com x 2,311,338 ops/sec ±0.83% (185 runs sampled) + parse support.google.com x 1,508,850 ops/sec ±0.86% (186 runs sampled) + parse www.google.com x 1,022,582 ops/sec ±1.32% (182 runs sampled) + parse youtu.be x 332,136 ops/sec ±1.02% (185 runs sampled) + parse youtube.com x 323,833 ops/sec ±0.77% (183 runs sampled) + +> node benchmark/parse.js + + cookie.parse - generic + + 6 tests completed. + + simple x 3,214,032 ops/sec ±1.61% (183 runs sampled) + decode x 587,237 ops/sec ±1.16% (187 runs sampled) + unquote x 2,954,618 ops/sec ±1.35% (183 runs sampled) + duplicates x 857,008 ops/sec ±0.89% (187 runs sampled) + 10 cookies x 292,133 ops/sec ±0.89% (187 runs sampled) + 100 cookies x 22,610 ops/sec ±0.68% (187 runs sampled) +``` + +## References + +- [RFC 6265: HTTP State Management Mechanism][rfc-6265] +- [Same-site Cookies][rfc-6265bis-09-5.4.7] + +[rfc-cutler-httpbis-partitioned-cookies]: https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/ +[rfc-west-cookie-priority-00-4.1]: https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1 +[rfc-6265bis-09-5.4.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7 +[rfc-6265]: https://tools.ietf.org/html/rfc6265 +[rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4 +[rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1 +[rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2 +[rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3 +[rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4 +[rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5 +[rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6 +[rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3 + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/cookie/master?label=ci +[ci-url]: https://github.com/jshttp/cookie/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master +[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master +[node-image]: https://badgen.net/npm/node/cookie +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/cookie +[npm-url]: https://npmjs.org/package/cookie +[npm-version-image]: https://badgen.net/npm/v/cookie diff --git a/node_modules/cookie/SECURITY.md b/node_modules/cookie/SECURITY.md new file mode 100644 index 0000000..fd4a6c5 --- /dev/null +++ b/node_modules/cookie/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `cookie` team and community take all security bugs seriously. Thank +you for improving the security of the project. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `cookie`. This +information can be found in the npm registry using the command +`npm owner ls cookie`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/jshttp/cookie/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/node_modules/cookie/index.js b/node_modules/cookie/index.js new file mode 100644 index 0000000..51a58cb --- /dev/null +++ b/node_modules/cookie/index.js @@ -0,0 +1,334 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var __toString = Object.prototype.toString + +/** + * RegExp to match cookie-name in RFC 6265 sec 4.1.1 + * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2 + * which has been replaced by the token definition in RFC 7230 appendix B. + * + * cookie-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / + * "*" / "+" / "-" / "." / "^" / "_" / + * "`" / "|" / "~" / DIGIT / ALPHA + */ + +var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +/** + * RegExp to match cookie-value in RFC 6265 sec 4.1.1 + * + * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + * ; US-ASCII characters excluding CTLs, + * ; whitespace DQUOTE, comma, semicolon, + * ; and backslash + */ + +var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/; + +/** + * RegExp to match domain-value in RFC 6265 sec 4.1.1 + * + * domain-value = + * ; defined in [RFC1034], Section 3.5, as + * ; enhanced by [RFC1123], Section 2.1 + * =